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