Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Why we can't do

List<Parent> mylist = ArrayList<child>(); 
like image 476
Ismail Marmoush Avatar asked Apr 23 '11 10:04

Ismail Marmoush


1 Answers

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.

like image 161
Jon Skeet Avatar answered Sep 20 '22 13:09

Jon Skeet