0
HashMap<String, ArrayList<? extends Serializable>> map = new HashMap<String, ArrayList<ArrayList>>();

This does not compile. To the best of my knowledge on Java Generics, it should. And this:

ArrayList<? extends Serializable> c = new ArrayList<ArrayList<String>>();

successfully compiles.

Can anyone say why the above wouldn't compile?

rgettman
  • 176,041
  • 30
  • 275
  • 357
Miy
  • 45
  • 7
  • Perhaps `ArrayList` doesn't extend `Serializable`? – Chol Nhial Mar 02 '18 at 01:49
  • Strongly related: [Java nested generic type](https://stackoverflow.com/questions/22806202/java-nested-generic-type) – rgettman Mar 02 '18 at 02:00
  • 1
    The fact that `A` extends (or implements) `B` doesn't imply that `HashMap` extends `HashMap`. After all, a `HashMap` is something that you can put a `B` in, but a `HashMap` isn't. Equivalent questions have been asked before. – Dawood ibn Kareem Mar 02 '18 at 02:12

1 Answers1

2

Why do you think that it should? A HashMap<String, Apple> is never assignable from a HashMap<String, Orange> for any possible unequal Apple and Orange, as long as both Apple and Orange are not wildcard-types.

And ArrayList<? extends Serializable> is not the same thing as ArrayList<ArrayList<?>>.

What you probably meant:

HashMap<String, ? extends ArrayList<? extends Serializable>> map = 
  new HashMap<String, ArrayList<ArrayList<?>>>();

Now it compiles, because indeed:

? extends Serializable // can be assigned from
          ArrayList<?>

and

? extends ArrayList<? extends Serializable> // can be assigned from
          ArrayList<          ArrayList<?>>
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93