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.
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.
The underlying HashMap
would be restricted to ArrayList
s, 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 ArrayList
s:
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:
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.