简体   繁体   中英

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. 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. 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

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:

// ! 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> .

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 . Not a subtype of <Foo> . Not a supertype of <Foo> .

Simple Generic types are not polymorphic

List<Parent> myList = new ArrayList<Child>() \\\\ Invalid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM