Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
List<Object> list = new ArrayList<String>()
When I use the above line compiler gives me type mismatch error. But as I underst
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. So why above statement is wrong. I am looking for an explanation.
Just replace:
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>();
One sentence, because
Generic types are not polymorphic
i.e., even though java.lang.String is a subtype of java.lang.Object polymorphism doesn't apply to generic types. It only applies to collection types. thus
java.lang.String
java.lang.Object
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
Why can't generic types be polymorphic?
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>. If such proposition holds, consistency of type system will be violated. Consider the following case:
A
B
List<A>
List<B>
// ! 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>
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 . Not a subtype of <Foo>. Not a supertype of <Foo>.
List<Foo>
<Foo>
supertype
Simple Generic types are not polymorphic
List<Parent> myList = new ArrayList<Child>() \\ Invalid
只需更换:
和
或者
在这里重要的是您使用相同的数据类型进行操作
或者你也可以使用