JDK-7014779 : Iterator for EnumSet.entrySet() returns results which cannot be used to build a Set<Map.Entry>
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic
  • CPU: generic
  • Submitted: 2011-01-26
  • Updated: 2011-02-02
  • Resolved: 2011-02-02
Related Reports
Duplicate :  
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());

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.

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.