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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值