I need help with a Java homework problem. I have two bags, say bag1
containing the strings A
, B
, C
and D
and bag2
containing strings E
, F
, G
and H
. I need to write a BagInterface for the union of those two bag then a class call ArrayBag<T> implements BagInterface<T>
.
BagInterface I was thinking something like this:
public interface BagInterface<T> {
public T union(T[] item);
}
public class ArrayBag<T> implements BagInterface<T> {
private final static int DEFAULT_CAP = 4;
private int numElements;
private T[] bag;
public ArrayBagR(int cap) {
bag = (T[]) new Object[cap];
this.numElements = 0;
}
public T union(T[] item) {
// Not sure how I should write this so I can pass
// another class object in the parameter
// Like say if I write a main to run this I could
// do something like Bag1.union(Bag2)
// and get something like A B C D E F G H
}
}
Like say if I have this
public static void main(String[] args) {
BagInterface bag1 = new ArrayBag(n);
BagInterface bag2 = new ArrayBag(m);
BagInterface<String> everything = bag1.union(bag2);
}
Per your example,
When you call,
union
onbag1
passingbag2
as argument,Now you can write something line. No need to return from this method.
bag1
will be updated with union.Please note: This is a pseudo code to share the concept (not a code).
A sample java code can be like below:
Also you can further use
List
methodcontains
to simplify the code as :If you don't want to update
bag1
contents, you should have method like this: