我已經閱讀了很多關於這一點,我知道:差異<?>
List<Object> listOfObject = new ArrayList<TYPE>(); // (0)
//can only work for TYPE == Object.
//if TYPE extends Object (and thus objects of type TYPE are Objects),
//this is not the same with Lists: List<Type> is not a List<Object>
現在我讀過,以下是確定:
List undefinedList = new ArrayList<TYPE>(); // (1)
//works for ANY type (except for primitives)
而且
List<?> wildcardList = new ArrayList<TYPE>(); // (2)
//also works for ANY type (except for primitives)
然後:
List undefinedlist = new ArrayList(); //no TYPE specified
undefinedList.add(new Integer(1)); //WORKS
undefinedList.add(new String("string")); //WORKS
但是:
List<?> wildcardList = new ArrayList<TYPE>(); //TYPE specified
wildcardList.add(new TYPE(...)); //COMPILER ERROR
例如:
List<?> wildcardList = new ArrayList<String>(); //TYPE specified
wildcardList.add(new String("string")); //COMPILER ERROR: The method add(capture#1-of ?) in the type List<capture#1-of ?> is not applicable for the arguments (String)
我不明白你爲什麼不能添加任何東西到wildcardList,因爲它的類型可以是任何東西。但是,爲什麼你可以添加到undefinedList? 他們似乎相同&顯示相同的行爲,給出(1)和(2)。
與幾乎任何問題一樣。實際顯示「編譯器錯誤」實際上是什麼(錯誤文本)總是更好。 – billjamesdev 2013-02-20 15:25:05
'?'不代表*任何*,但**未知**。 – m0skit0 2013-02-20 15:25:08
[java泛型未綁定通配符vs原始類型](http:// stackoverflow。com/questions/14242174/java-generics-unbound-wildcard-vs-raw-type) – 2013-02-20 15:25:14