'calling a method that will return the union of two array
This is the scenario.
The union of two collections consists of their contents combined into a new collection. Add a method union to the interface BagInterface for the ADT bag that returns as a new bag the union of the bag receiving the call to the method and the bag that is the method’s one argument. Include sufficient comments to fully specify the method. Note that the union of two bags might contain duplicate items. For example, if object x occurs five times in one bag and twice in another, the union of these bags contains x seven times. Specifically, suppose that bag1 and bag2 are Bag objects, where Bag implements BagInterface; bag1 contains the String objects a, b, and c; and bag2 contains the String objects b, b, d, and e.
After the statement
BagInterface<String> everything = bag1.union(bag2);
executes, the bag everything contains the strings a, b, b, b, c, d, and e. Note that union does not affect the contents of bag1 and bag2. Implement the union method in ArrayBag class.
This is my approach within in bag interface class.
public default ArrayList<T> union (T [] bag){
ArrayList<T> newArray = new ArrayList<>();
for (T e:bag){
newArray.add(e);
}
return newArray;
}
My code has a problem.
For example , I have an array list called hi = {"hi","bye"}.I want to execute the following code.
hi.union(anotherArray)
And this code will return the union of two array? I browsed the Internet but could not find a solution.I knew that union only takes in one parameter and how can I take the hi(declared front) into my method and combine them together?
Lastly, is my understanding towards the question correct?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
