【发布时间】:2017-11-01 20:49:15
【问题描述】:
我遇到了这种情况:
public abstract class Parent {
public Parent(){}
}
public class Child extends Parent{
public Child(){
}
}
public class Main {
public static void main(String[] args) {
HashMap<Child, Double> mapChild = new HashMap<>();
HashMap<Parent, Double> mapParent = new HashMap<>();
foo(mapChild, new Child()); //Wrong 1 arg type
foo(mapParent, new Child());
}
public static void foo(HashMap<Parent, Double> x, Parent parent){
x.put(parent, 5.0);
}
}
此代码不起作用,因为foo(mapChild, new Child()) 说 - “错误的参数类型”。
我用通配符尝试了一些东西,但我认为它不能用它。我可以创建第二个 foo 方法,但我不想重复代码。
有什么想法吗?
【问题讨论】: