I want to compare every object in an an ArrayList with every other object and remove an object from the list, once it was matched once, kind of like this:
List<Object> list = new ArrayList();
for(int i = 0; i<list.size();i++){
Object o1 = list.get(i);
for(int j = i+1; j<list.size();j++){
Object o2 = list.get(j);
if(match(o1, o2)){
// do something with o2
list.remove(j);
}
}
}
will this work, or could removing an object, that the first loop hasn't reached yet, cause problems?
Edit:
I tried using the Iterator approach, this seems to work (with a List of Strings as a test) without skipping items
for(int i = 0; i<list.size();i++){
String s1 = list.get(i);
Iterator<String> it = list.subList(i+1, list.size()).iterator();
while(it.hasNext()){
String s2 = it.next();
if(s1.equals(s2)){
it.remove();
System.out.println(list.toString());
}
}
}
thanks! (unless someone has anything else to add)