私はこれについてたくさん読んだことがあり、次のことを知っています:
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) を考えると、それらは同じように見え、同じ動作を示します。