簡體   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