Create generic collection of references to objects. --Java-- The class header wi
ID: 3748166 • Letter: C
Question
Create generic collection of references to objects. --Java--
The class header will be defined with a type parameter T that is used for the type of the bag elements. The static union() method will be declared with its own generic parameter E.
1. Declare the generic Bag class with the interface clause necessary for the
clone method
2. Declare a private field data such that it is an ArrayList object reference with the
generic element type T. It is optional to keep or omit the manyItems field, it is not
necessary for the ArrayList storage.
3. Add an accessor method (getter) for data
4. Define a constructor such that the field is initialized to the constructor’s
parameter;
5. Define another constructor such that it takes a parameter initialCapacity and
data is assigned an ArrayList instantiated to size intitialCapacity
6. add() : takes a T type element for parameter and adds that element to the bag.
Note that adding and removing elements means these same operations executed on the
field data.
7. addAll( ) : takes a generic Bag reference for parameter; the method checks if
the parameter bag is null or empty, if so the message “Nothing was added to the bag” is
printed to the console and the method returns; otherwise iterate over the parameter
and add all its elements to this bag, use an enhanced for loop.
8. addMany(): takes a generic vararg parameter; the
method returns if the parameter is null or empty, otherwise runs an enhanced for loop
on the parameter and adds its elements to this bag (ignore the compiler warning)
9. union( ): static; declares its own generic parameter E; the method takes two bag
references for parameter, creates and returns a new bag that contains all the elements
of both parameter bags. Use the constructor with the capacity parameter.
10. clone( ): goes by the template; in the try block once the bag is cloned you must
also clone the field data
11. remove( ): returns a Boolean; takes a T type parameter and removes one copy of
the parameter value from the bag by calling the remove method with respect to data
with the same parameter
12. removeAll( ): returns a Boolean; takes a T type parameter and removes all
copies of the parameter value occurring in the bag; calls the remove method with
respect to data. Note that this time you cannot simply pass the parameter the
removeAll method for data. The ArrayList class requires a Collection object for
parameter when its removeAll( ) method is called. Therefore you have to create another
ArrayList (a local variable in the method) named, say badBag such that badBag
contains exactly as many copies of the target value is it occurs in data;
countOccurrences( ) to be called, see below. Once badBag is loaded you can call
removeAll( ) with respect to data and with BadBag as parameter.
13. countOccurrences(): takes a target element for parameter and returns the
number of occurrences of target in the bag. Run an enhanced for loop for counting.
14. toString( ): the method runs an enhanced for loop concatenating the toString()
return values called with respect to all the elements in the bag; the concatenated string
is returned.
Note: toString does not need a separate documented test since it will be called in the
test of the other methods
15. size( ): calls size( ) of the ArrayList class (data).
16. trimToSize( ); calls trimToSize( ) of the ArrayList class (data).
17. Create an application class and test all methods!
- Instantiate two objects of the AL_Bag class, both for String type. Accordingly,
create two ArrayList objects and use them as parameters in the initializer
constructor
- Exercise the methods of the AL_Bag class and print the results to the console
with short explanations. For printing the bag content use the toString method
Explanation / Answer
Here is the required code for this problem in Java. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks
// AL_Bag.java
import java.util.ArrayList;
public class AL_Bag<T> implements Cloneable {
// attribute
private ArrayList<T> data;
/**
* constructor to initialize fields with values
*
* @param data
* array list containing initial data
*/
public AL_Bag(ArrayList<T> data) {
this.data = data;
}
/**
* constructor specifying capacity of array list
*/
public AL_Bag(int initialCapacity) {
this.data = new ArrayList<T>(initialCapacity);
}
/**
* @return the data list
*/
public ArrayList<T> getData() {
return data;
}
/**
* method to add an item
*/
public void add(T item) {
data.add(item);
}
/**
* method to add all items of another bag to this bag
*/
public void addAll(AL_Bag<T> otherBag) {
if (otherBag != null && otherBag.size() > 0) {
for (T itm : otherBag.data) {
add(itm);
}
} else {
System.out.println("Nothing was added to the bag");
}
}
/**
* method to add multiple items using variable arguments
*/
public void addMany(T... items) {
for (T itm : items) {
add(itm);
}
}
/**
* method to find union of two bags and return the new bag
*/
public static <E> AL_Bag<E> union(AL_Bag<E> bag1, AL_Bag<E> bag2) {
if (bag1 != null && bag2 != null) {
AL_Bag<E> newBag = new AL_Bag<E>(bag1.size() + bag2.size());
newBag.addAll(bag1);
newBag.addAll(bag2);
return newBag;
}
return null;
}
@Override
protected Object clone() {
try {
AL_Bag<T> bag = (AL_Bag<T>) super.clone();
bag.data = (ArrayList<T>) this.data.clone();
return bag;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
/**
* method to remove an item
*/
public boolean remove(T item) {
return data.remove(item);
}
/**
* method to remove all occurrences of an item
*/
public boolean removeAll(T item) {
ArrayList<T> tmpList = new ArrayList<T>();
for (int i = 0; i < countOccurrences(item); i++) {
tmpList.add(item);
}
// removing all copies of item
return data.removeAll(tmpList);
}
/**
* method to find number of occurrences of an item
*/
public int countOccurrences(T item) {
int count = 0;
for (T itm : data) {
if (itm.equals(item)) {
count++;
}
}
return count;
}
@Override
public String toString() {
String text = "[";
for (T item : data) {
text += item + " ";
}
text += "]";
return text;
}
/**
* method to find the current number of elements
*/
public int size() {
return data.size();
}
/**
* method to trim array list to size
*/
public void trimToSize() {
data.trimToSize();
}
}
// Test.java
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
// creating array lists to be used as initializers
ArrayList<String> list1 = new ArrayList<String>();
list1.add("Alice");
list1.add("Bob");
list1.add("Cindy");
list1.add("David");
ArrayList<String> list2 = new ArrayList<String>();
list2.add("Oliver");
list2.add("Parkman");
list2.add("Qyburn");
list2.add("Suresh");
list2.add("Tyrion");
/**
* creating two AL_Bag objects using the lists
*/
AL_Bag<String> bag1 = new AL_Bag<String>(list1);
AL_Bag<String> bag2 = new AL_Bag<String>(list2);
/**
* Testing the two lists thoroughly
*/
System.out.println("Bag1: " + bag1);
System.out.println("Bag2: " + bag2);
System.out.println("Bag1 size: " + bag1.size());
System.out.println("Bag2 size: " + bag2.size());
bag1.addMany("Bob", "John", "Mary");
System.out.println("Bag1 addMany(Bob,John,Mary): " + bag1);
System.out.println("Bag1 union Bag2: " + AL_Bag.union(bag1, bag2));
bag1.remove("Alice");
System.out.println("Bag1 remove(Alice): " + bag1);
bag1.removeAll("Bob");
System.out.println("Bag1 removeAll(Bob): " + bag1);
System.out.println("Bag1 clone: " + bag1.clone());
}
}
/*OUTPUT*/
Bag1: [Alice Bob Cindy David ]
Bag2: [Oliver Parkman Qyburn Suresh Tyrion ]
Bag1 size: 4
Bag2 size: 5
Bag1 addMany(Bob,John,Mary): [Alice Bob Cindy David Bob John Mary ]
Bag1 union Bag2: [Alice Bob Cindy David Bob John Mary Oliver Parkman Qyburn Suresh Tyrion ]
Bag1 remove(Alice): [Bob Cindy David Bob John Mary ]
Bag1 removeAll(Bob): [Cindy David John Mary ]
Bag1 clone: [Cindy David John Mary ]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.