Iterating over EnumMap#entrySet

前端 未结 3 2407
悲哀的现实
悲哀的现实 2021-02-20 18:06

Enumerating over Map#entrySet doesn\'t work as expected for all Map implementations, specially for EnumMap, IdentityHashMap and here is the sample code

3条回答
  •  天命终不由人
    2021-02-20 18:44

    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;.

提交回复
热议问题