4

is this possible? if not, why isn't this possible in Java?

interface B extends A {}
public List<B> getList();
List<A> = getList(); // Type mismatch: cannot convert from List<B> to List<A>

I think the topic I'm looking for is "covariant types" as here and here, but its murky and it doesn't solve my problem.

Community
  • 1
  • 1
Dustin Getz
  • 21,282
  • 15
  • 82
  • 131
  • 1
    Why exactly is `getList()` declared to return `List` in first place? Can't it be `List`? – BalusC Oct 07 '11 at 17:26
  • 1
    possible duplicate of [Is `List` a subclass of `List`? Why aren't Java's generics implicitly polymorphic?](http://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-arent-javas-generics-implicitl) – DJClayworth Oct 07 '11 at 17:34

3 Answers3

6

Here is an intuitive example of how this can make things go horribly wrong:

interface B extends A {}
List<B> blist=new List<B>();
List<A> alist=blist;
alist.add(new A()); //should be ok, right?
B b = blist.get(0); //fail: even though blist is a List<B>, it now has an A in it
Corey Kosak
  • 2,615
  • 17
  • 13
  • hmm. if i silence the compiler with `List extends A>`, it seems that this problem still exists? edit: no, i speculate error moves to L4. cool. – Dustin Getz Oct 07 '11 at 17:38
5

Try

List<? extends A> = getList()
gkamal
  • 20,777
  • 4
  • 60
  • 57
1

The reason you can't do this is that A and B are not the same, you have specified getList returns a List of B (not a super class or a sub class)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130