Question

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.

Was it helpful?

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.

OTHER TIPS

You don't need the outer for loop unless you need to pass something to the someotherclassfunction() from s. So changing the below;

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

to

someotherclassfunction();

should get rid of the ConcurrentModificationException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top