在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