Possible Duplicate:
Common elements in two lists
I am trying to take 2 lists of integers, and search the lists to find elements which are the same. A new list will then be created with all common elements. I am able to get it to find common elements at the same position but not at different positions. My code can be viewed below:
class Share {
public static void main(String[] args) {
ArrayList<Integer> oneList = new ArrayList<Integer>();
ArrayList<Integer> twoList = new ArrayList<Integer>();
oneList.add(8);
oneList.add(2);
oneList.add(5);
oneList.add(4);
oneList.add(3);
twoList.add(1);
twoList.add(2);
twoList.add(3);
twoList.add(4);
twoList.add(5);
System.out.println(sharedItems(oneList, twoList));
}
static List<Integer> sharedItems(List<Integer> list1, List<Integer> list2) {
Iterator<Integer> it1 = list1.iterator();
Iterator<Integer> it2 = list2.iterator();
int i1 = 0;
int i2 = 0;
ArrayList<Integer> shareList = new ArrayList<Integer>();
while (it1.hasNext()){
i1 = it1.next();}
System.out.println(i1);
while (it2.hasNext()){
i2 = it2.next();
if (i1 == i2){
shareList.add(i1);
}
}
return shareList;
}
}