[英]Why List<Object> list = new ArrayList<String>() this give TypeMismatch error
List<Object> list = new ArrayList<String>()
When I use the above line compiler gives me type mismatch error. 当我使用上述行编译器时,会给我类型不匹配错误。 But as I understand Object is super class of String and if I create list of object then it should also accept String.
但是据我了解,Object是String的超类,如果我创建对象列表,则它也应该接受String。 So why above statement is wrong.
那么,为什么上述说法是错误的。 I am looking for an explanation.
我正在寻找一个解释。
One sentence, because 一句话,因为
Generic types are not polymorphic
泛型类型不是多态的
ie, even though java.lang.String
is a subtype of java.lang.Object
polymorphism doesn't apply to generic types. 也就是说,即使
java.lang.String
是一个亚型java.lang.Object
多态性并不适用于泛型类型。 It only applies to collection types. 它仅适用于集合类型。 thus
从而
List<Object> list = new ArrayList<String>(); //this isn't valid
List<Object> list = new ArrayList<Object>(); //valid
List<? extends Object> list = new ArrayList<String>();//valid
Because you define what possible list can be associated with. 因为您定义了可能与之关联的列表。
The correct way would be 正确的方法是
List<?> list = new ArrayList<String>();
which is the same as 这与
List<? extends Object> list = new ArrayList<String>();
A
is a super type of B
does not imply List<A>
is a super type of List<B>
. A
是B
的超类型,并不意味着List<A>
是List<B>
的超类型。 If such proposition holds, consistency of type system will be violated. 如果这样的主张成立,类型系统的一致性就会受到侵犯。 Consider the following case:
考虑以下情况:
// ! This code cannot pass compilation.
List<String> list1 = new ArrayList<String>();
List<Object> list2 = list1; // Error
// Previous conversion causes type contradiction in following statements.
list2.add(new SomeOtherClass());
String v = list1.get(0); // list1.get(0) is not String!
That's why List<Object>
should not be super type of List<String>
. 这就是为什么
List<Object>
不应是List<String>
超类型。
Just replace: 只需替换:
List<Object> list = new ArrayList<String>()
with 与
List<String> list = new ArrayList<String>()
or 要么
List<Object> list = new ArrayList<Object>()
It is important here that you operate with the same data type 在此使用相同的数据类型进行操作很重要
Or you can also use 或者你也可以使用
List<?> list = new ArrayList<Object>();
The type of the variable declaration must match the type you pass to the actual object type. 变量声明的类型必须与您传递给实际对象类型的类型匹配。 If you declare
List<Foo>
foo then whatever you assign to the foo reference MUST be of the generic type . 如果声明
List<Foo>
foo,则分配给foo引用的任何内容都必须是通用类型。 Not a subtype of <Foo>
. 不是
<Foo>
的子类型。 Not a supertype
of <Foo>
. 不是
<Foo>
的supertype
。
Simple Generic types are not polymorphic
List<Parent> myList = new ArrayList<Child>() \\\\ Invalid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.