What basic operations on a Map are permitted while iterating over it?

前端 未结 4 994
既然无缘
既然无缘 2021-01-11 14:21

Say I am iterating over a Map in Java... I am unclear about what I can to that Map while in the process of iterating over it. I guess I am mostly confused by this warning in

4条回答
  •  独厮守ぢ
    2021-01-11 15:12

    If you take a look at the HashMap class, you'll see a field called 'modCount'. This is how the map knows when it's been modified during iteration. Any method that increments modCount when you're iterating will cause it to throw a ConcurrentModificationException.

    That said, you CAN put a value into a map if the key already exists, effectively updating the entry with the new value:

     Map test = new HashMap();
     test.put("test", 1);
    
     for(String key : test.keySet())
     {
         test.put(key, 2); // this works!
     }
    
     System.out.println(test); // will print "test->2"
    

    When you ask if you can perform these operations 'safely,' you don't have to worry too much because HashMap is designed to throw that ConcurrentModificationException as soon as it runs into a problem like this. These operations will fail fast; they won't leave the map in a bad state.

提交回复
热议问题