-
Bug
-
Resolution: Duplicate
-
P4
-
None
-
6
-
None
-
generic
-
generic
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.
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.
- duplicates
-
JDK-6312706 (coll) Map entrySet iterators should return different entries on each call to next()
- Closed