ConcurrentModificationException (Java)

Exception in thread "main" java.util.ConcurrentModificationException Squash the PC dirties the room Violet. The room state is now dirty Lily the animal growls The Animal Lily left the room and goes to Green through the west door. at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793) at java.util.HashMap$KeyIterator.next(HashMap.java:828) at homework5.Room.critReactRoomStateChange(Room.java:76) at homework5.PC.play(PC.java:121) at homework5.Main.main(Main.java:41) Java Result: 1 

This is the error I am getting.

My method looks like

 public void critReactRoomStateChange(String command, PC pc) { Creature temp = null; Iterator iterator = getCreatures().keySet().iterator(); while (iterator.hasNext()) { String names = iterator.next().toString(); if (!(getCreatures().get(names) instanceof PC)) { temp = getCreatures().get(names); if (temp != null) { temp.reactStateChange(command, pc); temp.checkNewRoom(); } } } } 

So, I understand, this means that I resize the iterator until it finishes, and this is the error you get. This is true since one of the actionStateChange is to remove an object from hashMap. How to do it safely, so when I delete something, it allows Iterator to know in advance so that I can avoid this error. Thank you in advance. If you need more information, I would be happy to satisfy your requests.

+4
source share
3 answers

The only safe way to remove an item from the base collection and continue the iteration is to use the remove() Iterator . This removes the last item returned by the next() Iterator .

In your case, it seems that for this you will need to pass Iterator method that performs the modification (or make it an instance field, for example, a Map object).

+8
source

You delete it with iterator.remove ().

+1
source

Another option is to use ConcurrentHashMap, which does not have this problem. You can use this as a replacement, and you do not need to change the rest of the code.

+1
source

All Articles