I am trying to write a generic function which will accept both of the following data types
Map <Integer, Map<Integer, Long>>
Map <Integer, Map<Integer, Double>>
My function looks like this,
function(Map<Integer, Map<Integer, ? extends Number>> arg) {}
But I am getting an incompatible type error. It works for a Map, but not for map of Maps. I am not able to understand why? Is there any way to do this?
First let’s reduce the problem by using
Sets instead:At first glance you might wonder why this assignment is illegal, since after all you can assign a
Set<Long>toSet<? extends Number>The reason is that generics are not covariant. The compiler prevents you from assigning aSet<Set<Long>>toSet<Set<? extends Number>>for the same reason it won’t let you assign aSet<Long>to aSet<Number>. See the linked answer for more details.As a workaround, you can use a type parameter in your method signature as other answers have suggested. You can also use another wildcard to make the assignment legal:
Or in your example: