简体   繁体   中英

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

class Enum is defined in API as:

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:

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:

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?

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

PS I researched SO, but found nothing DIRECTLY answering above question. My research:

  1. angelikalanger FAQ
  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? And please never use new Integer(54) . If for whatever reason you do not like autoboxing , use Integer.valueOf(54) instead. 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); 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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