gpt4 book ai didi

java - 值方法如何在枚举中工作

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:56:53 24 4
gpt4 key购买 nike

在 Enum 中,values() 方法如何工作?

values() 方法背后的逻辑是什么?

在我的项目中,我们将所有枚举数据缓存在 Map 中,如下所示:

public enum Actions {
CREATE("create"),
UPDATE("update"),
DELETE("delete"),
ACTIVE("active"),
INACTIVE("inactive"),
MANAGE_ORDER("manage"),
;


private static Map<String, Actions> actionMap;
static {
actionMap = new HashMap<String, Actions>(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 ?

阅读Oracle tutorial :

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 - 值方法如何在枚举中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17949471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com