我已经阅读了很多关于此的内容,并且我知道:
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)
我明白为什么你不能向通配符列表添加任何东西,因为它的类型可以是任何东西。但是,为什么可以添加到 undefinedList 中?给定(1)和(2),它们看起来相同并表现出相同的行为。