0

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)

  • 4
    If you want to remove things from a `List` while looping through it, get an `Iterator` from it, and use its `remove()` method. It's much safer than trying to manually remove things. – azurefrog Mar 24 '15 at 19:35
  • it shouldn't cause an error because it updates the size of the list – Code Whisperer Mar 24 '15 at 19:36
  • @azurefrog should I use an Iterator for each loop (which seems like it could cause problems) or just one for the inner loop? – Matthias Wadlinger Mar 24 '15 at 19:44
  • 1
    For better or worse: if you wish to have a Collection that contains unique elements, this is exactly what a Set is for. Create a HashSet (for example), adding all the items from the List a voila. – copeg Mar 24 '15 at 19:44
  • Well, honestly I wouldn't use loops at all. Like @copeg mentions, there are things built in to Java which already do this for you (i.e. `Set`s). Take a look at [this question](http://stackoverflow.com/questions/2849450/how-to-remove-duplicates-from-a-list); its answers cover a wide variety of ways to "de-duplicate" items in a `List`. (such as `List dedupedlist = new ArrayList<>(new LinkedHashSet<>(listwithdupes));`). – azurefrog Mar 24 '15 at 19:47
  • Yes, this could cause problems; you'll skip over the element that was moved into position `j`. This is why you should use the `Iterator` approach. – Louis Wasserman Mar 24 '15 at 19:51
  • I'm not trying to remove duplicates though, I want to match similar objects (that contain Strings) – Matthias Wadlinger Mar 24 '15 at 19:51

0 Answers0