2013-10-09 37 views
0

我有一個B類和C這兩種擴展A類:使用Java泛型與HashMap的

public class B extends A {...} 
public class C extends A {...} 

如何使用Java泛型有一個HashMap這種方式?

B b = new B(); 
C c = new C(); 

Map<String, ? extends A> map = new HashMap<String, A>(); 

map.put("B", b); 
map.put("C", c); 

Eclipse中始終顯示錯誤:

The method put(String, capture#1-of ? extends A) in the type Map is not applicable for the arguments (String, B)

The method put(String, capture#1-of ? extends A) in the type Map is not applicable for the arguments (String, C)

+5

只需使用'地圖'。 – GriffeyDog

回答

5

只要改變HashMap的類型<String, A>

Map<String, A> map = new HashMap<String, A>(); 
+0

那麼,我做到了......但那是什麼通配符? List appleList = new ArrayList (); List <?擴展水果> list = appleList; ? –

+1

請參閱官方文檔:http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html。它對通配符有一個有趣的解釋。還有一個關於http://stackoverflow.com/questions/252055/java-generics-wildcards的解釋(查看所有答案)。那麼,如果答案有幫助並解決了你的問題,不要忘記檢查它是否被接受。 – Trein