第一种:直接使用
EnumMap em = new EnumMap(C.class); em.put(C.UK,"春暧花开"); em.put(C.US, 233); System.out.println(em);
此种EnumMap允许插入各种类型的值。由于java自动包装机制,甚至可以插入整数等基本类型。
同时eclipse提示:Type safety: The method put(Enum, Object) belongs to the raw type EnumMap. References to generic type EnumMap<K,V> should be parameterized
第二种:继承 EnumMap 类
1 import java.util.EnumMap;2 3 public class Phons extends EnumMap{4 public Phons() {5 super(C.class);6 }7 }
如果向其中插入无关类型。编译报错:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method put(C, Phon) in the type EnumMap<C,Phon> is not applicable for the arguments (C, int)此种方法避免了类型安全的问题。