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


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>();
4

5 回答 5

6

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

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?

于 2013-02-18T11:40:24.803 回答
1

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>();

于 2013-02-18T11:44:23.497 回答
1

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

于 2013-02-18T12:07:12.840 回答
0

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

于 2013-02-18T11:44:40.587 回答
0

只需更换:

List<Object> list = new ArrayList<String>()

List<String> list = new ArrayList<String>()

或者

List<Object> list = new ArrayList<Object>()

在这里重要的是您使用相同的数据类型进行操作

或者你也可以使用

 List<?> list = new ArrayList<Object>();
于 2013-02-18T11:40:01.897 回答