2

Possible Duplicate:
Concurrent Modification Exception : adding to an ArrayList

I'm attempting to remove duplicate values from an arraylist with this method:

 public void hasDuplicates(List<Artifact> p_cars) {
    final List<String> usedNames = new ArrayList<String>();
    for (Artifact car : p_cars) {
        final String name = car.getObjectId();

        if (usedNames.contains(name)) {
            p_cars.remove(car);

        }

        usedNames.add(name);
    }

}

How can I remove these duplicate values without concurrent modifying the arraylist?

I'm doing this on an arraylist that populates a listview if that helps with the context.

Thanks!

Community
  • 1
  • 1
Atma
  • 29,141
  • 56
  • 198
  • 299
  • Side note: the method should be named "removeDuplicates", and it should use a Set to track the used names. – JB Nizet May 17 '12 at 17:36
  • What @JB said... or `usedNames.add(name)` should be in an `else { }` block. – Dilum Ranatunga May 17 '12 at 17:41
  • @Dilum: putting it in an else block would still lead to O(n) lookups rather than O(1) with a HashSet. A Set is the natural choice for unique values. – JB Nizet May 17 '12 at 17:44

1 Answers1

6

You can't modify a collection while you are iterating over it. The only exception is using the remove method of the iterator:

 public void hasDuplicates(List<Artifact> p_cars) {
    final List<String> usedNames = new ArrayList<String>();
    Iterator<Artifact> it = p_cars.iterator();
    while (it.hasNext()) {
        Artifact car = it.next();
        final String name = car.getObjectId();

        if (usedNames.contains(name)) {
            it.remove();

        } else {
            usedNames.add(name);
        }
    }

}
Pablo
  • 3,655
  • 2
  • 30
  • 44
  • This is the correct way to modify a collection you are iterating over. However, for this usecase, we need to know just how big p_cars is, and how many duplicates are expected. – Dilum Ranatunga May 17 '12 at 17:43