Why we can't do List<Parent> mylist = ArrayList<child>();

JavaGenericsInheritanceCollections

Java Problem Overview


Why we can't do

List<Parent> mylist = ArrayList<child>();

Java Solutions


Solution 1 - Java

Suppose we could. Then this program would have to be fine:

ArrayList<Banana> bananas = new ArrayList<Banana>();
List<Fruit> fruit = bananas;
fruit.add(new Apple());

Banana banana = bananas.get(0);

That's clearly not type safe - you've ended up with an apple in the collection of bananas.

What you can do is:

List<? extends Fruit> fruit = new ArrayList<Banana>();

this is safe, because the compiler won't then let you try to add to the list of fruit. It knows that it's a list of some kind of fruit, so you could write:

Fruit firstFruit = fruit.get(0);

but it doesn't know what exact kind of fruit it's a list of, and make sure you can't do the wrong thing.

See the Java generics FAQ another explanation.

Solution 2 - Java

Because they're not the same type. Suppose you had another child class of Parent (Child2 for the sake of argument), it would then be possible to put an instance of Child2 into a List<Parent>, but type-incorrect to put it into an instance of List<Child>. Covariant inheritance is a real headache, and is only supported at all in Java for array types (where it can cause odd problems).

Solution 3 - Java

It should be this way, because we can do: Parent A = new Child();

Edit : Wait, actually it works :

List<Parent> list = new ArrayList<Parent>(); List<ChildA> tmp = new ArrayList<ChildA>(); list.addAll(tmp); List<ChildB> tmp2 = new ArrayList<ChildB>(); list.addAll(tmp2);

It's just that the direct cast is not supported.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIsmail MarmoushView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaDonal FellowsView Answer on Stackoverflow
Solution 3 - JavaEpiFoulouxView Answer on Stackoverflow