user7336033
user7336033

Reputation: 297

Why getting ConcurrentModificationException in HashMap

I have a code like below to loop through the hashmap but I am getting error

ConcurrentModificationException

for (String i : currentItems.keySet()) //I am hitting error in this line
   {
         items.put(i,currentItems.get(i));
         currentRoom.removeItem(i);
         System.out.println(items.get(i));
   }

I would appreciate any suggestion in the above.

Upvotes: 0

Views: 40

Answers (1)

Thiyanesh
Thiyanesh

Reputation: 2360

  1. Java does not allow modifying collections while iterating over them
  2. For any use case requiring modification while iterating, please use Iterator

Please refer to this question

Upvotes: 2

Related Questions