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)

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM