In my application I have used a Map to store POJO objects. As per the requirement I need to iterate over the keySet of the Map and remove objects which dont need any modification.
Conside the code below:
public void remove(Map<String,User> removeUser){
Set<String> keySet = removeUser.keySey();
User user = null;
for(String key : keySet){
user = (user) removeUser.get(key);
if(!user.isActive()){
removeUser.remove(key);
}
}
}
Here in above code, I am getting ConcurrentModificationException when I try to fetch User object after Object removal.
Can anyone tell me why it’s happening?
I have not used multi threading.So not able to understand, from where it generated ConCurrentModification Exception.
Even I tried with HashMap and Hashtable, but the problem still exist.
It came from the line where you are trying to remove the element from your
Mapwhile iterating over itsKeySet.You should not do that. If you want to modify your
CollectionorMap, use aniterator.See this very nice post – efficient-equivalent-for-removing-elements-while-iterating-the-collection explaining the problems that can come while modifying the collection you iterate upon.
Here’s a simple code explaining how you can use it here: –
OUTPUT: –