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?

3
  • Perhaps ArrayList<String> doesn't extend Serializable? Commented Mar 2, 2018 at 1:49
  • Strongly related: Java nested generic type Commented Mar 2, 2018 at 2:00
  • 1
    The fact that A extends (or implements) B doesn't imply that HashMap<K,A> extends HashMap<K,B>. After all, a HashMap<K,B> is something that you can put a B in, but a HashMap<K,A> isn't. Equivalent questions have been asked before. Commented Mar 2, 2018 at 2:12

1 Answer 1

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<?>>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I took your advice and it indeed works now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.