Search code examples
javaexceptioncollectionsconcurrentmodification

concurrent modification exception for set iterator


Hi I have the following code structure

    Private Set<String> someset = null; //a class variable

    someclassfunction() {
       Set<String> st = mapA.keyset();
       someset = mapA.keyset();

       for (String s: st) { //this is where now the exception occurs
            someotherclassfunction();
       }
    }

    someotherclassfunction() {
       Iterator<String> it = someset.iterator();
       while (it.hasNext()) {
           String key = it.next();
           if (somecondition) {
               it.remove();
           //Earlier I did, someset.remove(key), this threw concurrent
           //modification exception at this point. So I found on stack 
           //overflow that we need to use iterator to remove
           }
       }
    }

But now the same exception occurs on the calling function for each loop. Why is that? I am not modifying the st set, I am modifying the someset (class variable). Please help.


Solution

  • With this code:

    Set<String> st = mapA.keyset();
    someset = mapA.keyset();
    

    Both someset and st point to the same set. So you're actually removing from the set you're iterating upon in the for-each loop in your first method.