java中,enum 的用法
阿新 • • 發佈:2018-11-03
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方法