-2

Why do I have a ConcurrentModificationException? I am iterating over the objects of a set and removing them in another set:

  public static void printSubsets(Set<String> set){
    if (set.isEmpty()) return;
    printSet(set);

    Set<String> copy = set;
    for (String s: set){
      copy.remove(s);
      printSubsets(copy);
      copy.add(s);
   }
  }
2
  • 2
    What do you think Set<String> copy = set; does and why? Feb 2, 2015 at 23:53
  • hint, assignment != copy. Feb 3, 2015 at 0:07

1 Answer 1

1

No, you are removing them from the same Set, because there is only one Set object here. You have 2 variables referring to the same Set, set and copy.

set -----> Set object
copy ------^

Any changes you make are visible through either variable. You are removing elements from the Set while you're iterating over them with an enhanced for loop, so a ConcurrentModificationException results.

To prevent this, you can make a (shallow) copy of the set.

Set<String> copy = new HashSet<String>(set);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.