nios nios - 1 year ago 45
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
like this :

HashMap<ObjectA, List<ObjectB>> hashMap = new HashMap<>();
//populate 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 ?

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 Source

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>>


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.