1

I have the following interface and class definitions...

abstract interface I{}

class Foo implements I{}

abstract class A<T extends I> {
    List<T> list;
}

class B extends A<Foo> {}

All the definitions work fine. I then want to do the following:

A b = new B();
List<? extends I> iList = b.list;

The compiler will indeed give me an Unchecked Assignment warning... but why? Won't all of A's lists be of type <? extends I>? b.list always has elements that extend I, so I am having trouble seeing why there would be an error

Daiwik Daarun
  • 3,804
  • 7
  • 33
  • 60
  • 4
    `A` is a [raw type](http://stackoverflow.com/q/2770321/1079354) at declaration. – Makoto Apr 14 '15 at 03:38
  • 1
    But won't all of `A`'s lists be of type ` extends I>`? – Daiwik Daarun Apr 14 '15 at 03:39
  • Nope - there's no guarantee of type safety with raw types, so anything to do with generics is completely off the table now. – Makoto Apr 14 '15 at 03:40
  • 1
    @DaiwikDaarun that's a good question. You should add it to the text of your question instead of in a comment. That will make it much more interesting and different from the duplicate. – Erwin Bolwidt Apr 14 '15 at 03:43
  • Is there a way to get unmarked as a duplicate? I still don't see any counterexamples to my comment, and now edit – Daiwik Daarun Apr 14 '15 at 03:46

1 Answers1

2

The variable A b is of a raw type. Perhaps you meant to use A<Foo> b instead.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
  • Both good fixes, but does anyone see why? won't all of `A`'s lists be of type ` extends I>`? – Daiwik Daarun Apr 14 '15 at 04:01
  • @DaiwikDaarun An `A` is not an `A extends I>`, since you know that the generic type is more specific than that. – chrylis -cautiouslyoptimistic- Apr 14 '15 at 06:11
  • @DaiwikDaarun, I think its answered in the comments to your question. Basically define A as a generic type and then the Unchecked warning goes away from the second statement List extends I> iList = b.list; – ramp Apr 14 '15 at 06:17