如何将HashMap <parent,double =“”>“强制转换”为HashMap <child,double =“”>

时间:2017-11-01 20:49:16

标签: java generics hashmap

我有这种情况:

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())表示“错误的参数类型”  我尝试使用Wildcards,但我认为它无法使用它。我可以创建第二个foo方法,但我不想重复代码。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

使用

  

<? extends Parent>

在你的收藏中。因此,该集合可以接受Child和Parent。

答案 1 :(得分:1)

我相信你想要的是

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

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