简体   繁体   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);

class Enum is defined in API as:类 Enum 在 API 中定义为:

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

I have我有

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

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

Question 1:问题 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

Question 2:问题2:

this compiles:这编译:

        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);

But can I add anything in angle brackets of RHS (new EnumMap), like I did for map1 above?但是我可以在 RHS(新 EnumMap)的尖括号中添加任何内容,就像我在上面的 map1 中所做的那样?

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

PS I researched SO, but found nothing DIRECTLY answering above question. PS我研究了SO,但没有发现直接回答上述问题。 My research:我的研究:

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

First: please use this instead:第一:请改用这个:

Cards e = Cards.Clubs;

Second: Use the diamond operator .第二:使用菱形运算符 If you absolutely want, it is new EnumMap<Cards, Integer>() but why do you want to write it out?如果你绝对想要,它是new EnumMap<Cards, Integer>()但是你为什么要写出来呢? And please never use new Integer(54) .并且请永远不要使用new Integer(54) If for whatever reason you do not like autoboxing , use Integer.valueOf(54) instead.如果出于某种原因您不喜欢autoboxing ,请改用Integer.valueOf(54) It doesn't waste objects . 它不会浪费对象

So, I recommend this code:所以,我推荐这个代码:

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

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

The first thing is:第一件事是:

Enum<Cards> e = Cards.Clubs;

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

But I don't know why the Map<Enum<Cards>, Integer> map2 = new EnumMap<>(map1);但我不知道为什么Map<Enum<Cards>, Integer> map2 = new EnumMap<>(map1); fails失败

Edit:编辑:

So I think what you want is something like this:所以我认为你想要的是这样的:

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);

You don't need to wrap you Enum into an Enum你不需要把你的 Enum 包装成一个 Enum

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

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