【问题标题】:Why does HashMap.Entry not take generics parameters of its parent?为什么 HashMap.Entry 不采用其父级的泛型参数?
【发布时间】:2022-01-09 13:59:33
【问题描述】:

我有一个 HashMap 类型的对象。但是 HashMap.Entry.getValue() 仍然返回对象。它不尊重其父 HashMap 的泛型参数。这同样适用于 getKey()。

示例如下:

class Main extends HashMap<String, String>
{
    public static void main(String[] args)
    {
        Main m = new Main();
        m.put("key", "value");
    
        for (Main.Entry e : m.entrySet())
            String s = e.getValue(); // this line throws an error telling that getValue() returns Object and not String
    }
}

【问题讨论】:

  • 因为您声明了原始类型的 e 变量。省略类型参数并不意味着“嘿javac,请推断类型参数”。

标签: java generics


【解决方案1】:

不要定义原始条目,也输入它

for (Main.Entry<String, String> e : m.entrySet()) {
    String s = e.getValue();
}

【讨论】:

  • 是的,如果您使用的是 Java10+,请使用 var
  • @azro 这不是我的问题的答案。我的问题是为什么这是必要的,因为 java 编译器必须知道类定义中的泛型参数。
猜你喜欢
  • 1970-01-01
  • 2010-09-20
  • 2021-05-06
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
  • 2012-11-17
  • 1970-01-01
相关资源
最近更新 更多