nios nios - 3 months ago 7
Java Question

Issue with interface as Map key & value

In a library project, I have :

public interface InterfaceA {
}

public interface InterfaceB {
}

public void myMethod(Map<? extends InterfaceA, List<? extends InterfaceB>> map) {
//do something
}


Then I have another project (having this library as a dependency) that contains two object implementing these interfaces :

public class ObjectA implements InterfaceA {
}

public class ObjectB implements InterfaceB {
}


When I try to call the library method
myMethod
like this :

HashMap<ObjectA, List<ObjectB>> hashMap = new HashMap<>();
//populate hashmap
myMethod(hashMap);


I get a compilation warning saying there is an argument mismatch.

What am I missing here ? Does it have something to do with the map ?

EDIT :
The exact error (it's not a warning actually) is :

incompatible types: HashMap<ObjectA,List<ObjectB>> cannot be converted to Map<? extends InterfaceA,List<? extends InterfaceB>>

Answer

Generics are invariant.

If your method declares:

Map<? extends InterfaceA, List<? extends InterfaceB>>

Then the second type parameter has to be exactly List<? extends InterfaceB>.

You can fix it by using:

Map<? extends InterfaceA, ? extends List<? extends InterfaceB>>

Instead.


As a side note about //populate hashmap. In that case your Map is a consumer, and you would want to use super instead:

Map<? super InterfaceA, ? super List<? super InterfaceB>>

See this question about PECS.