java - different generic type-erasure behaviour for Hashmap and EnumMap -
i noticed surprising(for me) difference between hashmap
, enummap
in 'generics behaviour'.
what mean?
consider following 2 code snippets:
snippet 1
enum types { a, b, c } enum wrong { } public class test { public static void main(string... args) { enummap<types, integer> m = new enummap<types, integer>(types.class); enummap m1 = m; m1.put(wrong.a, 1); } }
out:
exception in thread "main" java.lang.classcastexception: class wrong != class types
snippet 2
enum types { a, b, c } enum wrong { } public class test { public static void main(string... args) { hashmap<types, integer> m = new hashmap<types, integer>(); hashmap m1 = m; m1.put(wrong.a, 1); } }
out:
successful compilation!
conclusion:
therefore hashmap
erasure fullfils same code enummap
- not. why?
your conclusion incorrect: erasure occurs in both cases, , in same way. difference enummap object keeps reference class object key type in field, , uses class object perform reflective cast. causing exception, can tell stacktrace.
in contrast, ordinary map uses unchecked cast, succeeds if object of incorrect type (giving rise heap pollution).
Comments
Post a Comment