Use:
HashMap<ArrayList<Integer>, ? extends Number>
instead of:
HashMap<ArrayList<Integer>, Number>
to declare the super type of:
HashMap<ArrayList<Integer>, ANYTHING_EXTENDING_NUMBER>
Therefore:
HashMap<ArrayList<Integer>, ? extends Number> hashMap1 =
new HashMap<ArrayList<Integer>, Integer>(); //Compiles OK.
HashMap<ArrayList<Integer>, Number> hashMap2 =
new HashMap<ArrayList<Integer>, Integer>(); //Does not compile.
Generally, remember, that in Generics, T<Parent>
is not a super type of T<Child>
; rather T<? extends Parent>
is a super type of T<Child>
.
One thing to bear in mind is the Capture Problem, that is, you will not be able to add the elements of the subtype you use as a generic type argument.
For example, this:
ArrayList<Integer> arrayList = new ArrayList<>();
Integer integer = new Integer(5);
HashMap<ArrayList<Integer>, ? extends Number> hashMap
= new HashMap<ArrayList<Integer>, Integer>();
will work fine;
however, this afterwards:
hashMap.put(arrayList, new Integer(3)); //Does not work.
will not work.
Have a look at this section from Java tutorial.