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

GrowinMan picture GrowinMan · Jan 5, 2012 · Viewed 11.4k times · Source

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/10/difference-between-hashmap-and.html

However I don't completely get it. Can someone elaborate this? Perhaps with an example?

Thanks for looking in!

Answer

evanwong picture evanwong · Jan 5, 2012

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
    }