java在枚举方法中调方法_java – 值方法如何在枚举中工作
在Enum中value()方法如何工作?
values()方法背后的邏輯是什么?
在我的項目中,我們將所有枚舉數據緩存在Map中,如下所示:
public enum Actions {
CREATE("create"),
UPDATE("update"),
DELETE("delete"),
ACTIVE("active"),
INACTIVE("inactive"),
MANAGE_ORDER("manage"),
;
private static Map actionMap;
static {
actionMap = new HashMap(values().length);
for(Actions action : values()) {
actionMap.put(action.getName(), action);
}
}
public static Actions fromName(String name) {
if(name == null)
throw new IllegalArgumentException();
return actionMap.get(name);
}
private String name;
private Actions(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
這是使用枚舉的最佳做法嗎?
解決方法:
In Enum how values() method work ?
The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.
另外需要注意的是,如果你使用枚舉作為鍵,最好使用EnumMap.
A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.
標簽:java
來源: https://codeday.me/bug/20190723/1509014.html
總結
以上是生活随笔為你收集整理的java在枚举方法中调方法_java – 值方法如何在枚举中工作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 拉结尔6月21日服务器维护,拉结尔6月2
- 下一篇: 【libsvm 错误使用mex】