# Finding the difference of two arrays using arrayList

• 11-17-2012, 02:08 PM
keithf
Finding the difference of two arrays using arrayList
Right, so I am trying to find the answer to the above question and then return it as type IntSet. For this question, I need to use arrayList. I have tried tweaking the code a number of times, however, the array contains the wrong elements. The intersection method called works perfectly fine, so the problem is not there. I think it is when I am trying to remove elements from the list that the problems start. Your help is much appreciated. UPDATE: I have now managed to return an array, however all the remove element method does is take away 3 from the array.

Code:

public IntSet difference(Integer[] s1, Integer[] s2) {

IntSet result = intersection(s1, s2);//get intersection array
IntSet s3;
Arrays.sort(s1);//sort arrays
ArrayList<Integer> difference = new ArrayList(Arrays.asList(s1));//creates new array
ArrayList<Integer> outcome = new ArrayList(Arrays.asList(result));
int[] s4 = new int[result.al.size()];
int counter = 0;
for (int int2 : result.al) {
s4[counter++] = int2;
}
int count2 = outcome.size();
for (int i = 0; i < count2; i++) {
if (difference.contains(s4[i])!= false) {
removeElement(s4[i],difference);
count2--;
}

}
s3 = new IntSet(difference);
return s3;
}

public int removeElement(int elem, ArrayList<Integer> am) {

if (!am.contains(elem)) {
return NUMBER_NOT_IN_SET;

}
am.remove(elem);
return NUMBER_REMOVED;
}

• 11-18-2012, 04:40 PM
Fou-Lu
You're over-thinking what you need to do with this.
Since you already have a method to intersect, and you can cast to a list, its simple to remove what is in a collection from another.
PHP Code:

public static Integer[] difference(Integer[] lhsInteger[] rhs)
{

ArrayList<IntegeralResult = new ArrayList<Integer>(Arrays.asList(lhs));

alResult.removeAll(Arrays.asList(intersect(lhsrhs)));

return
alResult.toArray(new Integer[alResult.size()]);
}

That assumes that the intersect's returned IntSet is castable to a list as you have here in your example.
Unless I misunderstand what you are referring to as the difference, that should do what you are needing.