简体   繁体   中英

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

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> List<? extends InterfaceB> .

You can fix it by using:

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

Instead.

You either modify your Hashmap creation for this:

Map<? extends InterfaceA, List<? extends InterfaceB>> hashMap = new HashMap<>();

or modify your method definition for this:

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

将您的地图声明为

HashMap<ObjectA, List<? extends InterfaceB>> hashMap = new HashMap<ObjectA, List<? extends InterfaceB>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM