Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-7014779

Iterator for EnumMap.entrySet() returns results which cannot be used to build a Set<Map.Entry>

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • 6
    • core-libs
    • None

      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.

            Unassigned Unassigned
            mduigou Mike Duigou
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: