1
HashMap<Integer,List<Integer>> test = new HashMap<Integer,ArrayList<Integer>>();

This line gives me the error: HashMap<Integer,ArrayList<Integer>> cannot be converted to HashMap<Integer,List<Integer>>

I don't understand why this doesn't work.

varimax
  • 111
  • 1
  • 13

2 Answers2

2

The underlying HashMap would be restricted to ArrayLists, but the reference would allow you to add any kind of list. What if you tried to add a LinkedList to the HashMap?

Probably, you just need to make a HashMap of List:

HashMap<Integer, List<Integer>> test = new HashMap<Integer, List<Integer>>();

Or if you really want the restriction that it only contain ArrayLists:

HashMap<Integer, ArrayList<Integer>> test = new HashMap<Integer, ArrayList<Integer>>();

Note that this kind of issue is called covariance and contravariance.

See Also:

This link is about C# instead of Java, but is one of the best explanations of the concept I'm aware of. It won't apply in the same way to Java as it does to C#, but it should be a useful read nevertheless:

Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
0

It does not work because it is "unsafe", and the reason it is unsafe is because you would be hold two reference to the same list with this two types:

HashMap<Integer,List<Integer>> a;
HashMap<Integer,ArrayList<Integer>> b;

So if you are presented with prospective value typed LinkedList<Integer> it would be ok to add it two a but it wouldn't be ok to add it to b since a LinkedList is not an ArrayList. So by creating the a reference out of b you are creating a back-door to corrupt the content of the map from b reference perspective.

For example down the line someone pulling values from b that is expecting ArrayList will get a LinkedList instead causing a casting exception.

Valentin Ruano
  • 2,726
  • 19
  • 29