I am expecting a ConcurrentModificationException in the follow code, but it's working fine.
HashMap<Integer, String>table1 = new HashMap<Integer, String>();
table1.put(1, "Sam");
table1.put(2, "Jon");
table1.put(3, "Doe");
Iterator itr1 = table1.entrySet().iterator();
table1.put(3, "DONN");
while(itr1.hasNext())
{
System.out.println("---Value--" + itr1.next());
}
As per the JavaDoc for HashMap:
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.
So since I am modifying the HashMap after getting the Iterator I should be getting the ConcurrentModificationException. Why is it not throwing?
Putting an entry for an existing key is not considered a structural modification in the current implementation of HashMapand will never trigger a ConcurrentModificationException. Try putting with a new key, e.g. table1.put(4, "UPS"); to get a ConcurrentModificationException.
You are modifying the HashMap not the entrySet that you are obtaining on it, and here you are obtaining the iterator over the entrySet:
As per entrySet method javaDoc:
If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined.
So you are not getting ConcurrentModificationException.
Here is the full explaination of entrySet:
Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With