I’ve a collection type:
Collection<A> collecA
And I’ve a list in my object:
List<B> listB
Where B is extending A
class B extends A { ... }
But I can’t do the following:
collecA = listB
I can’t understand why since Collection is implemented by List.
Let’s assume for a moment you could do what you describe:
The method call
collecA.add(new A())appears okay sincecollecAis a collectionthat holds
As. However, if the above assignment were allowed, then we have aproblem because
collecAis really reference to aList<B>instance – I justadded an
Ainto a list that can only holdBs!Asker also said:
It doesn’t matter that Collection is a superclass of List. This assignment is illegal even if you used two lists.
The key is that the
List<A>variable can reference onlyLists that can holdAs. However, aList<B>instance cannot holdAs. Therefore, aList<A>variable likelistAcannot be assigned a reference to aList<B>instance referred to bylistB.Or more generally speaking:
Bbeing a subclass ofAdoes not imply thatSomeGenericClass<B>is a subclass ofSomeGenericClass<A>(JLS §4.10: Subtyping does not extend through generic types:T <: Udoes not imply thatC<T> <: C<U>.)It was this example/analogy from the Java Generics Tutorial that helped me understand this:
“Understanding why becomes much easier if you think of tangible objects — things you can actually picture — such as a cage:
But what about an “animal cage”? English is ambiguous, so to be precise let’s assume we’re talking about an “all-animal cage”:
This is a cage designed to hold all kinds of animals, mixed together. It must have bars strong enough to hold in the lions, and spaced closely enough to hold in the butterflies.
…
Since a lion is a kind of animal (Lion is a subtype of Animal), the question then becomes, “Is a lion cage a kind of animal cage? Is
Cage<Lion>a subtype ofCage<Animal>?”. By the above definition of animal cage, the answer must be “no”. This is surprising! But it makes perfect sense when you think about it: A lion cage cannot be assumed to keep in butterflies, and a butterfly cage cannot be assumed to hold in lions. Therefore, neither cage can be considered an “all-animal” cage:“