public static <E> ArrayList<E> union
(ArrayList<E>array1, ArrayList<E>array2)
{
//arrayUnion will be the arrayList that will be returned
ArrayList <E> arrayUnion = new ArrayList <E>(array1);
arrayUnion.addAll(array2);
E current;
for(int i = 0; i < arrayUnion.size(); i++)
{
for(int j = 0; j < arrayUnion.size(); j++)
{
current = arrayUnion.get(i);
if(current.equals(arrayUnion.get(j)))
{
arrayUnion.remove(j);
}
}
}
return arrayUnion;
}
For my test of this method, this was the output:
The first list is [ww, ee, rr, t, yy]
The second list is [ww, ss, ee, dd]
The union of both ArrayLists is: [ee, t, ww, dd]
What went wrong..? I’ve been stuck on this for far too long and I never want to hear the word Union again. Plz help
Your code has to do check the current item is checked with itself. If not you have to remove the item and decrease the
jwith one as you have to check again the item replaced atj. I have modified your code to work for your case. Just look at the condition check for item to be removed.