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