首页 > 学院 > 开发设计 > 正文

EnumMap 两种使用方式的比较

2019-11-14 21:04:50
字体:
来源:转载
供稿:网友
EnumMap 两种使用方式的比较

第一种:直接使用

        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<C, Phon> {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)

此种方法避免了类型安全的问题。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表