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!

3
  • Side note: the method should be named "removeDuplicates", and it should use a Set<String> to track the used names. Commented May 17, 2012 at 17:36
  • What @JB said... or usedNames.add(name) should be in an else { } block. Commented May 17, 2012 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. Commented May 17, 2012 at 17:44

1 Answer 1

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);
        }
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.