Enumerating over Map#entrySet doesn\'t work as expected for all Map implementations, specially for EnumMap, IdentityHashMap and here is the sample code
The problem is not with the map but with the implementation of EntryIterator and the HashSet specification that accept only not equal elements.
In case 1 and 2 maps should have two elements, you can verify that calling
map.entrySet().size();
The 'problem' is in the implementation of EntryIterator by EnumMap class, as this is a puzzle try to figure out itself why.
ps. use debugger.
Edit:
This is what you are really doing is:
Set> set = new HashSet>();
Iterator> e = entrySet.iterator();
while (e.hasNext()) {
set.add(e.next());
}
Remember that HashSet is implemented over HashMap, the values added to hashMap based on hashcode and equality.
BTW Everything in explained in OP link to the puzzle. The bug is in the equal method that after second invocation of method next(), change the way of working and compare the class type than a values return o == this;.