简体   繁体   English

界面作为地图键和值的问题

[英]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 : 当我尝试像这样调用库方法myMethod

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> 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: 您可以为此修改Hashmap创建:

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>>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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