作者:蔚蓝的希望_674 | 来源:互联网 | 2023-05-25 21:29
我正在尝试Java接口,以下代码给出了错误.
在类中,构造函数将Map作为参数
public class ClassA{
private Map testMap;
ClassA(Map testMap){
this.testMap=testMap;
}
}
public class ClassB{
ClassA testA = new ClassA(new HashMap); //1st declaration
Map testMap=new HashMap(); //Second declaration
ClassA testB = new ClassA(testMap);
}
ImplmntsInterfaceA
是一个实现的类InterfaceA
.
这两个ClassA
声明都给出了错误,首先建议将Map构造函数更改为,HashMap
然后再次要求将InterfaceA
泛型替换为ImplmntsInterfaceA
.
有人可以帮忙解决它为什么不起作用?
谢谢 :)
1> Jon Skeet..:
我怀疑你想要改变Map
到Map
的ClassA
构造函数签名(及场).否则,HashMap
真的不是它的有效论据.
考虑哪些操作有效Map
- 你可以写:
map.put("foo", new SomeArbitraryImplementationOfA());
这对于a无效,Map
因为后者的值必须是a ImplmntsInterfaceA
.编译器正在保护您.
如果您使用Map
,您将无法在其中进行任何写入操作ClassA
(因为您不知道哪些值有效),但您将能够从地图中获取,因为知道每个值至少实现InterfaceA
.
这基本上是一个更复杂的版本,为什么一个List
不是List
...