0

Why does this not compile?

Map<Integer, List<String>> myMap;
myMap = new HashMap<Integer, ArrayList<String>>();

With the error:

Type mismatch: cannot convert from HashMap<Integer,ArrayList<String>> to
Map<Integer,List<String>>

Why can't I use a generic as a generic?

It's not like I'm asking the difference between List<Dog> and List<Animal>. Contract between List<String> and ArrayList<String> should match.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
littleca
  • 1
  • 1
  • 1
    Because `List` is not the same as `ArrayList` in the generic declaration. – Luiggi Mendoza Apr 02 '15 at 21:01
  • 3
    After reading the possible duplicate Q/A, you should understand the difference between `List` and `List`. Now, from the same example, replace `Dog` by `List` and replace `Animal` by `ArrayList`. Then you got your answer. – Luiggi Mendoza Apr 02 '15 at 21:06
  • `HashMap>();` is not a subtype of (nor is it convertible to) `Map>` and is therefore not assignable to it. – Sotirios Delimanolis Apr 02 '15 at 21:09
  • General rule of thumb: Only specify the implementing type of a `List`/`Map` when you're creating said list/map. In this case, you're creating the `HashMap`, but not the `ArrayList`. – Powerlord Apr 02 '15 at 21:11

0 Answers0