I am trying to find items that occur in two sets. I have to use Sets, that is why I am not using any other libraries, etc.
My code is the following:
public static void intersection (ArrayList<Integer>s1, ArrayList<Integer>s2) {
HashSet <Integer> all = new HashSet<Integer>();
HashSet <Integer> both = new HashSet<Integer>();
for (int i=0; i<s1.size(); i++)
all.add(s1.get(i));
for (int x=0; x<s2.size(); x++) {
if ((!(all.add(s2.get(x)))) && (((all.contains(s2.get(x)))))) {
both.add(s2.get(x));
}
}
System.out.println("intersection - "+ both);
}
The arraylists contain the following values:
s1: 4 5 5 6 76 7 7 8 8 8 8 8
s2: 23 3 4 3 5 3 53 5 46 46 4 6 5 3 4
However, the output is the following:
3, 4, 5, 6, 46
My desire output is:
4, 5, 6
I understand that it is adding 3 and 46 because to the ArraySet
both because those are elements present in the s2 ArrayList
but not in s1. However, I added all.contains(s2.get(x))
to make sure that the number added is present in s1 or HashSet
all. Why is not working?