0
List<? extends Number> ls = new ArrayList<Number>(); //(1)
Map <String,List<? extends Number>> mp = new HashMap<String,List<Number>>(); //(2)
Map <String,List<? extends Number>> mp = new HashMap<String,List<? extends Number>>(); //(3)

I can do (1) and (3) but not (2).

If I can do (1) why I am getting an error when doing (2)

1
  • If you're using java 7+ you can just do new HashMap<>(); Commented Sep 2, 2014 at 18:45

1 Answer 1

1

Even though a List<Number> is a List<? extends Number>, a HashMap<String, List<Number>> is not a Map<String, List<? extends Number>, because Java's generics are invariant. This is the same thing that makes a List<Dog> not assignable to a List<Animal>, even if Dog extends Animal. Here, List<Number> plays the part of the Dog and List<? extends Number> plays the part of the Animal.

List<Number> can't match List<? extends Number> when used as a type parameter.

You can get (2) to compile by introducing a wildcard: Change

Map <String,List<? extends Number>> mp = new HashMap<String,List<Number>>();

to

Map <String, ? extends List<? extends Number>> mp = new HashMap<String,List<Number>>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.