1
我試圖一類T
類型映射到ArrayList
也T
類型:Java映射類的ArrayList
Map<Class<?>, ArrayList<?>> map_ = new HashMap<Class<?>, ArrayList<?>>();
的問題是,我不能添加一個項目從本地圖檢索的Arraylist
:
map_.put(A.class, new ArrayList<A>());
A item = new A();
map_.get(item.getClass()).add(item); //failure!
我該如何構建我的地圖,以便我可以訪問並添加到它包含的數組列表?
看一看[Java Tutorials:Wildcards](http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html) –
您不能安全地進行此類操作。接受需要在某處進行未經檢查的投射。 –
相關:http://stackoverflow.com/questions/1473444/can-generics-allow-the-java-compiler-to-check-the-type-of-keys-and-values-in-am/1473482#1473482 –