我读过很多这方面的内容,我知道:
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)
And
List<?> wildcardList = new ArrayList<TYPE>(); // (2)
//also works for ANY type (except for primitives)
Then:
List undefinedlist = new ArrayList(); //no TYPE specified
undefinedList.add(new Integer(1)); //WORKS
undefinedList.add(new String("string")); //WORKS
However:
List<?> wildcardList = new ArrayList<TYPE>(); //TYPE specified
wildcardList.add(new TYPE(...)); //COMPILER ERROR
example:
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),它们看起来相同并表现出相同的行为。
List undefinedList
and List<?> wildcardList
正如您自己发现的那样,两者并不相同。第一个是原始类型,第二个是无界通配符。
如果您想使用泛型类型但不知道或不关心实际类型参数是什么,请使用无界通配符。您不能将任何内容(除了 null )放入此列表中,并且您所知道的关于从中获得的元素是它们扩展了 Object (实际上List<?>
是相同的List<? extends Object>
)。无界通配符很有用,因为如果你天真地将某些东西声明为List<Object>
,例如你不能分配List<String>
给它,同时你可以分配一个List<String>
to a List<?>
您应该(几乎)永远不需要使用原始类型,它们仅用于与 Java 5 之前编写的代码兼容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)