【问题标题】:Use enum that implements interface as parameter as key in EnumMap使用实现接口的枚举作为参数作为 EnumMap 中的键
【发布时间】:2018-04-02 12:22:02
【问题描述】:

我想拥有一系列扩展 BaseClass 的子类,而 BaseClass 又定义了一个 EnumMap。根据我插入此代码的 IDE。它告诉我构造函数

EnumMap<B, Integer>()

未定义,分别B不在指定范围内。

interface A {}
enum B implements A {hello, world}

abstract class BaseClass {
    protected EnumMap<? extends A, Integer> baseMap;
}

class ChildClass extends BaseClass {
    public ChildClass () {
        baseMap = new EnumMap<B,Integer>();
    }
}

例如倒数第三行给我带来了麻烦。我看不出有什么问题。

【问题讨论】:

    标签: java enum-map


    【解决方案1】:

    EnumMapthe constructor 中取enum

    baseMap = new EnumMap<B,Integer>(B.class);
    

    因为我们在post Java 7 world

    baseMap = new EnumMap<>(B.class);
    

    我建议在声明中使用Map - 程序到interface

    protected Map<? extends A, Integer> baseMap;
    

    【讨论】:

    • 谢谢,它部分起作用了 :) 两个问题:1.) 我现在如何将对象放入地图中,baseMap.put(B.hello, 10); 给了我一个奇怪的错误消息... 2.) 为什么建议在此示例中映射 EnumMap,尤其是因为我已经知道我想使用枚举类型键?
    • 对于 2) 因为它们不是enum,它们是A - 这是interface,没有理由其他东西无法实现它。对于 1) 由于PECS,您不能调用将? extends 作为参数的方法 - 如果您想使用put(),则需要使用Map&lt;A, Integer&gt;
    • @Felix.C 考虑到关于 SO 的协方差/反方差问题的数量,你远不是唯一这么想的人......
    • 它仍然在挣扎 :( 我使用 protected Map&lt;A, Integer&gt; baseMap;new EnumMap&lt;B,Integer&gt;(B.class);。我的意思是 B 是 A 而 EnumMap 是地图,为什么这不起作用?
    • 因为,如您所知,A 不是 EnumMap&lt;A, Integer&gt;Map&lt;B, Integer&gt; 不同...
    猜你喜欢
    • 2017-02-03
    • 2020-10-26
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2019-12-27
    • 2019-06-03
    • 1970-01-01
    • 2015-08-26
    相关资源
    最近更新 更多