如何"cast" HashMap<Parent, Double> to HashMap<Child, Double>



我遇到这种情况:

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 方法,但我不想复制代码。

有什么想法吗?

我相信你想要的是

public static <T> void foo(Map<T, Double> x, T t) {
  x.put(t, 5.0);
}

。不要实际Parent对象放入Map<Child, Double>.

使用

<? extends Parent>

在您的收藏中。因此,该集合可以同时接受子项和父项。

最新更新