Java枚举,如何通过code获取枚举?

通过code获取枚举时,可以通过枚举的values()方法去循环遍历,但是每次取得时候去循环难免会影响速率,建议用第二种方式,将枚举放到map中,通过键值对取数据会快很多。

public enum MaterialOutEnterEnum{
    BE_PUT_IN_STORAGE(1, "入库"),
    DELIVERY_OF_CARGO_FROM_STORAGE(2, "出库");

    private int code;
    private String value;

    MaterialOutEnterEnum(int code, String value) {
        this.code = code;
        this.value = value;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

	// 方式一、每次取枚举用for循环遍历
    public static MaterialOutEnterEnum getByCode(int code) {
        for (MaterialOutEnterEnum it : MaterialOutEnterEnum.values()) {
            if (it.getCode() == code) {
                return it;
            }
        }
        return null;
    }
    // 方式二、放入map中,通过键取值
 	private static Map<Integer,MaterialOutEnterEnum > zyMap = new HashMap<>();
    static {
        for (MaterialOutEnterEnum value : MaterialOutEnterEnum .values()) {
            zyMap.put(value.getCode(),value);
        }
    }
    public static MaterialOutEnterEnum getByCode(Integer code){
        return zyMap.get(code);
    }

}

你可能感兴趣的:(Java,spring,java,枚举,Enum)