5

why the following code is wrong in Java?

List<List<Integer>> list = new ArrayList<ArrayList<Integer>>();

I know List<List<Integer>> list = new ArrayList<List<Integer>>() is correct.

villion
  • 71
  • 1
  • 5
  • 2
    (The duplicate is actually simpler, because it's not "doubly generic" like this one is - but if you understand that, you can apply it to this easily. Basically, consider what `list.add(new LinkedList())` is doing to an object which was created as (and may still be *referenced* as) `ArrayList>`.) – Jon Skeet Mar 25 '15 at 20:56
  • This has been asked several times in the past. In fact, @JonSkeet has answered it more than once. His answer [here](http://stackoverflow.com/q/2745265) is, in my opinion, better than his answer in the one that he closed this as a duplicate of, despite how much I _loathe_ having `Dog extends Animal` as an example in any question about inheritance. – Dawood ibn Kareem Mar 25 '15 at 21:54

1 Answers1

0

Because generic types in Java are not covariant.

Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40