2 回答

TA貢獻1874條經驗 獲得超12個贊
潛在解決方案
在檢查枚舉及其可能性之后,有一種方法可以將值分配給枚舉中的鍵,如下所示。
創建一個新枚舉并分配 Key,例如公共枚舉 Color{RED;}。
向其添加構造函數參數,例如公共枚舉 Color{RED(“red”);}
向枚舉添加構造函數,例如公共枚舉 Color{RED(“red”);Color(){}}
在枚舉中添加一個名為值的新字段,例如私有字符串值;public String getValue() {return value;}
在枚舉的構造函數中設置字段值,例如 Color(String value) {this.value = value;}
Enum以這種方式工作,對于您添加的每個Key,它都會創建一個鏈接到Key的新實例字段 String值,然后它將使用您聲明的構造函數來保存該值。
全面實施
public enum Color
{
//[PROP]
RED("red"),
GREEN("green"),
BLUE("blue");
private String value;
public String getValue {return value;}
//[BUILD]
Color(String value) {this.value = value;}
//[UTIL]
Color[] getKeys() {return this.values;} //values method is already a method existing in enum class, we are just proposing another method name here as a facade for simplicity.
}
如果我們想檢索一個項目,我們只需執行Color.RED.value,這樣只有現有的鍵返回想要的值。
請注意,值不必是鍵的名稱,但可以是完全不同的值。
如果您有任何更簡單的解決方案,而不會給解決方案帶來更多復雜性,請發表評論。

TA貢獻1776條經驗 獲得超12個贊
這些鍵在所有地圖中都是唯一的。添加重復的鍵,然后它將被覆蓋。各種映射實現之間的差異涉及空鍵的可能性,迭代順序和并發問題。
示例:
Map hm = new HashMap(); hm.put("1", new Integer(1)); hm.put("2", new Integer(2)); hm.put("3", new Integer(3)); hm.put("4", new Integer(4)); hm.put("1", new Integer(5));// value integer 1 is overwritten by 5
此外,Map鍵是通用的,你可以放你想要的,而不僅僅是字符串,示例:
Map<Integer, String> hm = new HashMap<>(); hm.put(10, "1");
添加回答
舉報