java中,enum 的用法

enum用于类似字典的功能

用法参考以下代码

public enum ColorType {

    RED("1","红色"), YELLOW("2","黄色"), GREEN("3","绿色");

    private String code;
    private String value;

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

    public static String getValueByCode(String code) {
        ColorType[] values = ColorType.values();
        for (ColorType type : values) {
            if (type.code.equalsIgnoreCase(code)) {
                return type.value;
            }
        }
        return null;
    }

    public static String getCodeByValue(String value) {
        ColorType[] values = ColorType.values();
        for (ColorType type : values) {
            if (type.value.equalsIgnoreCase(value)) {
                return type.code;
            }
        }
        return null;
    }



    public static void main(String[] args) {
        System.out.println(ColorType.GREEN.code);
        System.out.println(ColorType.GREEN.value);

        String code=ColorType.getCodeByValue("黄色");
        System.out.println("code="+code);

        String value=ColorType.getValueByCode("1");
        System.out.println("value="+value);

    }

}

运行main方法

猜你喜欢

转载自blog.csdn.net/howard789/article/details/81513803