1

Possible Duplicate:
Java Generics: Cannot cast List<SubClass> to List<SuperClass>?

I'm just wondering why the following java code doesn't compile:

List<Object> c1 = new ArrayList<String>();

The error is: cannot convert from ArrayList <String> to List<Object>

String extends Object, so I would have thought that with polymorphism, as String "is a" Object that the String could be substituted for Object.

I'm just starting to learn java so hopefully this question makes sense.

thanks in advance...

Community
  • 1
  • 1

3 Answers3

1

You can do this

List<? extends Object> list=new List<String>();

objects has inheritance, but generics are a bit different.

MarekM
  • 1,426
  • 17
  • 14
0

Thsi dosnt work like this, The common parent here is List and not the element type stored in that List. therefor the two types are not really related. Take a look at this

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0

That's the case normally but not for generics. Generics are used to specify exactly what object is contained inside a collection. You can read more about them here.

Chris B
  • 925
  • 4
  • 14