• Post Reply Bookmark Topic Watch Topic
  • New Topic

ConcurrentModificationException error when attempting to remove a key-value from a HashMap  RSS feed

 
Noffica Rostt
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have such a HashMap:



When I try to remove a key-value pair with the following method, I see a java.util.ConcurrentModificationException error:



I feel there is just one small issue that I can't identify here.
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because HashMap implementation for iteration is fail fast. You are trying to remove an entry while iterating (using foreach). See the HashMap documentation for the same. Here is
the words from it:

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way
except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator
fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
 
Dennis Grimbergen
Ranch Hand
Posts: 159
IntelliJ IDE Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to remove an element of a collection during iteration, then explicitely use an iterator for your 'Set<String> yearAndFieldKeySet'.
During iteration you can call iterator.remove(element).
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another thing about Iterators: they should be local variables not fields, and should go out of scope immediately after they have been finished with.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!