繁体   English   中英

地图<Enum, Integer> map2 = 新的 EnumMap<what-to-write-to-make-compile???> (地图1);

[英]Map<Enum, Integer> map2 = new EnumMap<what-to-write-to-make-compile???>(map1);

类 Enum 在 API 中定义为:

public abstract class Enum<E extends Enum<E>>

我有

enum Cards { Trefs(2.3), Clubs(1.0);
    public double d;

    private Cards(double val) {
        this.d = val;
    }       
}   

问题 1:

Enum e = Cards.Clubs; //compiles, but with warning: "References to generic type Enum<E> should be parameterized"

Enum<???what-shall-I-write-here??> e1 = Cards.Clubs; //Question 1

问题2:

这编译:

        Map<Enum, Integer> map0 = new HashMap<Enum, Integer>();
        Map<Enum, Integer> map1 = new HashMap<Enum, Integer>();
        map1.put(Cards.Clubs, new Integer(54));

        Map<Enum, Integer> map2 = new EnumMap<>(map1);

但是我可以在 RHS(新 EnumMap)的尖括号中添加任何内容,就像我在上面的 map1 中所做的那样?

Map<Enum, Integer> map2 = new EnumMap<???what-can-I-write-here??>(map1);

PS我研究了SO,但没有发现直接回答上述问题。 我的研究:

  1. Angelikalanger 常见问题
  2. 这个
  3. 这个
  4. 这个
  5. 这个

第一:请改用这个:

Cards e = Cards.Clubs;

第二:使用菱形运算符 如果你绝对想要,它是new EnumMap<Cards, Integer>()但是你为什么要写出来呢? 并且请永远不要使用new Integer(54) 如果出于某种原因您不喜欢autoboxing ,请改用Integer.valueOf(54) 它不会浪费对象

所以,我推荐这个代码:

Map<Cards, Integer> map0 = new HashMap<>();
Map<Cards, Integer> map1 = new HashMap<>();
map1.put(Cards.Clubs, 54);

Map<Cards, Integer> map2 = new EnumMap<>(map1);

第一件事是:

Enum<Cards> e = Cards.Clubs;

Map<Enum<Cards>, Integer> map0 = new HashMap<>();
Map<Enum<Cards>, Integer> map1 = new HashMap<>();
map1.put(Cards.Clubs, 54);

但我不知道为什么Map<Enum<Cards>, Integer> map2 = new EnumMap<>(map1); 失败

编辑:

所以我认为你想要的是这样的:

Cards e = Cards.Clubs;

Map<Cards, Integer> map0 = new HashMap<>();
Map<Cards, Integer> map1 = new HashMap<>();
map1.put(Cards.Clubs, 54);

EnumMap<Cards, Integer> map2 = new EnumMap<>(map1);

你不需要把你的 Enum 包装成一个 Enum

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM