我已经阅读了很多相关内容,我知道:
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),它们看起来相同并且表现相同。
?
并不意味着任何东西,而是表示未知。 - m0skit0