Map <enum,integer =“”> map2 = new EnumMap <what-to-write-to-make-compile ???>(map1);

时间:2017-01-22 16:30:17

标签: java generics enums

类枚举在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);

P.S。我研究了SO,但没有发现任何 DIRECTLY 回答以上的问题。 我的研究:

  1. angelikalanger FAQ
  2. this
  3. this
  4. this
  5. this

2 个答案:

答案 0 :(得分:1)

首先:请改用:

Cards e = Cards.Clubs;

第二:使用diamond operator。如果你绝对想要,它是new EnumMap<Cards, Integer>(),但你为什么要把它写出来? 请不要使用new Integer(54)。如果由于某种原因您不喜欢autoboxing,请改用Integer.valueOf(54)It doesn't waste objects

所以,我推荐这段代码:

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

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

答案 1 :(得分:0)

首先是:

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