Why List<String> is not acceptable as List<Object>?
This question already has an answer here:
This generic question in Java may look confusing to any one who is not very familiar with Generics as in first glance it looks like String is object so List<String>
can be used where List<Object>
is required but this is not true. It will result in compilation error.
It does make sense if you go one step further because List<Object>
can store anything including String
, Integer
etc but List<String>
can only store Strings
.
Also have a look at: Why not inherit from List<T>?
Because while String
extends Object
, List<String>
does not extend List<Object>
Update:
In general, if Foo
is a subtype (subclass or subinterface) of Bar
, and G
is some generic type declaration, it is not the case that G<Foo>
is a subtype of G<Bar>
.
This is because collections do change. In your case, If List<String>
was a subtype of List<Object>
, then types other than String
can be added to it when the list is referenced using its supertype, as follows:
List<String> stringList = new ArrayList<String>;
List<Object> objectList = stringList;// this does compile only if List<String> where subtypes of List<Object>
objectList.add(new Object());
String s = stringList.get(0);// attempt to assign an Object to a String :O
and the Java compiler has to prevent these cases.
More elaboration on this Java Tutorial page.
你可以把一个错误类型的对象放到列表中,如果这个工作正常的话:
private void doSomething(List<Object> list) {
list.add(new Integer(123)); // Should be fine, it's an object
}
List<String> stringList = new ArrayList<String>();
doSomething(stringList); // If this worked....
String s = stringList.get(0); // ... you'd receive a ClassCastException here
链接地址: http://www.djcxy.com/p/53926.html
上一篇: 保护ArrayList不受写入权限的限制