【问题标题】:How to "cast" HashMap<Parent, Double> to HashMap<Child, Double>如何将 HashMap<Parent, Double> 转换为 HashMap<Child, Double>
【发布时间】: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 方法,但我不想重复代码。

有什么想法吗?

【问题讨论】:

标签: java generics hashmap


【解决方案1】:

我相信你想要的是

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

...不是实际上Parent 对象放在Map&lt;Child, Double&gt; 中。

【讨论】:

  • 更好的是Map&lt;? super T, Double&gt;
  • @Turing85:不。对于这个用例,它们是等价的; T 将被提升为适当的类型。
  • 确实如此。我花了一段时间说服自己,但似乎extendssuper 对一个泛型参数是多余的。
  • 这样的extends Parent 是正确/有用的吗:public static &lt;T extends Parent&gt; void foo(...)
  • 可以,但是当没有任何逻辑真正关心时,为什么还要添加约束呢?
【解决方案2】:

使用

&lt;? extends Parent&gt;

在您的收藏中。所以集合可以同时接受 Child 和 Parent。

【讨论】:

  • 这实际上是错误的方法。最好在第二个参数(parent)中将foo(...) 方法设为泛型,并将Map 设置为&lt;? super T&gt;(其中T 是第二个参数的类型)。
  • 他说了任何想法。那是我的。只是为了让您知道如果没有第一句话,您的评论会好得多。我们都在这里分享想法。具有不同的水平和技能。我没有考虑接受的解决方案。我很高兴其他人这样做了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多