United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
Bug ID: JDK-7014779 Iterator for EnumSet.entrySet() returns results which cannot be used to build a Set<Map.Entry>
JDK-7014779 : Iterator for EnumSet.entrySet() returns results which cannot be used to build a Set

Details
Type:
Bug
Submit Date:
2011-01-26
Status:
Closed
Updated Date:
2011-02-02
Project Name:
JDK
Resolved Date:
2011-02-02
Component:
core-libs
OS:
generic
Sub-Component:
java.util
CPU:
generic
Priority:
P4
Resolution:
Duplicate
Affected Versions:
6
Fixed Versions:

Related Reports
Duplicate:

Sub Tasks

Description
per Joshua Bloch:

public class Size {
    private enum Sex { MALE, FEMALE }

    public static void main(String[] args) {
        printSize(new HashMap<Sex, Sex>());
        printSize(new EnumMap<Sex, Sex>(Sex.class));
    }

    private static void printSize(Map<Sex, Sex> map) {
        map.put(Sex.MALE,   Sex.FEMALE);
        map.put(Sex.FEMALE, Sex.MALE);
        map.put(Sex.MALE,   Sex.MALE);
        map.put(Sex.FEMALE, Sex.FEMALE);
        Set<Map.Entry<Sex, Sex>> set =
            new HashSet<Map.Entry<Sex, Sex>>(map.entrySet());
        System.out.println(set.size());
    }
}

Predict the behavior of this program.  Then run it and see what happens.  Only two Map implementations display this disturbing behavior: EnumMap and IdentityHashMap.  I'm less disturbed by IdentityHashMap, as it's such an esoteric implementation.  But I could easily imagine someone getting hurt by the behavior demonstrated by the example above.  Fixing it would decrease the performance of iterating over entrySets of EnumMaps, but I think it would probably be worthwhile. I violated the principle of least astonishment here, and engaged in premature optimization.  Mea culpa, twice.

                                    

Comments
EVALUATION

All entrySet Map.Entry objects returned by the iterator are the same object which causes any set created from the iterator to contain zero (if the entrySet() is empty) or one element if the Set contains at least 1 entry.
                                     
2011-01-26



Hardware and Software, Engineered to Work Together