What do you exactly mean by HashMap's iterator is fail-fast and HashTable's enumerator isn't?

后端 未结 3 1802
失恋的感觉
失恋的感觉 2021-02-03 10:31

I was looking up the difference between the two classes and this point came up in a lot of the answers with this blog being the source: http://javarevisited.blogspot.com/2010/1

3条回答
  •  佛祖请我去吃肉
    2021-02-03 11:13

    Fail-fast means when you try to modify the content when you are iterating thru it, it will fail and throw ConcurrentModificationException.

    Set keys = hashMap.keySet();
    for (Object key : keys) {
        hashMap.put(someObject, someValue); //it will throw the ConcurrentModificationException here
    } 
    

    For HashTable enumeration:

     Enumeration keys = hashTable.keys();
     while (keys.hasMoreElements()) {
              hashTable.put(someKey, someValue);  //this is ok
        }
    

提交回复
热议问题