为什么List不能作为List
在Java中,这个泛型问题可能对于那些对泛型不太熟悉的人来说可能会感到困惑,因为乍一看,似乎String是Object,所以List<String>
可以在需要List<Object>
的地方使用,但这是错误的。这将导致编译错误。
如果进一步思考,这是有道理的,因为List<Object>
可以存储任何东西,包括String、Integer等,但List<String>
只能存储String。
问题不完全在于调用者可以存储任何类型的对象,真正的问题是,如果允许这样做,调用者将无法确定是否有一个String实例,因此必须像在没有泛型的时代一样处理它(使用instanceof操作符)。
解决这个问题的方法之一是使用通配符。可以使用`List extends Object>`来表示可以存储任何类型的对象的列表,包括String。这样,就可以将`List
另一个解决方法是在需要使用`List
总之,`List
List
For example, consider the following code:
private void doSomething(List
In this code, the method `doSomething` takes a List
However, if it were possible to pass a List
To maintain type safety, Java does not allow List
To solve this issue, you can use wildcard generics. Instead of using List
private void doSomething(List> list) { // list.add(new Integer(123)); // This would cause a compilation error } ListstringList = new ArrayList (); doSomething(stringList); // This works fine String s = stringList.get(0); // No ClassCastException here
By using List> instead of List