枚举类型
枚举类型是基于基本数据类型(不是构造数据类型)的类型。
枚举中的常量用法
public enum Type { red, green, blue }
/** * 枚举类型,整型,字符串之间转换 */ public class TypeMain { public static void main(String[] args) { System.out.println("输出枚举值:" + Type.blue); System.out.println("枚举类型转换成字符串:" + Type.blue.name()); System.out.println("枚举类型转换成字符串:" + String.valueOf(Type.blue)); System.out.println("字符串转换成枚举型:" + Type.valueOf("blue")); System.out.println("枚举类型转成整型:" + Type.blue.ordinal()); System.out.println("枚举类型转成整型,长度:" + Type.blue.values().length); System.out.println("整型转换成枚举类型:" + Type.blue.values()[2]); for (int i = 0; i < Type.blue.values().length; i++) { System.out.print(Type.blue.values()[i] + "\t"); } System.out.println(); } }
枚举中添加新 ***
import java.util.Objects; public enum AdviceTypeEnum { NRS(1, "NRS2002筛查"), MNA(2, "MNA-SF筛查"), STRESS(3, "合并与应激状况"), INTAKE(4, "摄入史调研"), GASTROINTESTINAL(5, "营养启动方式"), PATHWAY(6, "一般评估表"), GENERAL(7, "PG-SGA主观营养状况评估"), PGSGA(8, "体格检查"), PHYSIQUE(9, "胃肠道功能评价"), UNKNOWN(0, "未知"); // 值 private Integer value; // 显示名 private String display; private AdviceTypeEnum(int value, String display) { this.value = value; this.display = display; } public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } public String getDisplay() { return display; } public void setDisplay(String display) { this.display = display; } /** * @param value * @return */ public static AdviceTypeEnum fromValue(Integer value) { for (AdviceTypeEnum one : AdviceTypeEnum.values()) { if (Objects.equals(value, one.getValue())) { return one; } } return AdviceTypeEnum.UNKNOWN; } /** * @param value * @return */ public static AdviceTypeEnum fromValue(String value) { return AdviceTypeEnum.fromValue(Integer.parseInt(value)); } /** * @param display * @return */ public static AdviceTypeEnum fromDisplay(String display) { for (AdviceTypeEnum one : AdviceTypeEnum.values()) { if (Objects.equals(display, one.getDisplay())) { return one; } } return AdviceTypeEnum.UNKNOWN; } }
import java.util.HashMap; import java.util.Map; public class AdviceTypeEnumDemo { public static void main(String[] args) { AdviceTypeEnum adviceTypeEnum = AdviceTypeEnum.fromValue(1); System.out.println(adviceTypeEnum.getDisplay()); System.out.println(adviceTypeEnum.getValue()); AdviceTypeEnum adviceTypeEnum2 = AdviceTypeEnum.fromValue("1"); System.out.println(adviceTypeEnum2.getDisplay()); System.out.println(adviceTypeEnum2.getValue()); String type = "NRS2002筛查"; AdviceTypeEnum adviceTypeEnum3 = AdviceTypeEnum.fromDisplay(type); System.out.println(adviceTypeEnum3.getDisplay()); System.out.println(adviceTypeEnum3.getValue()); // if else Map<Integer, String> paramsMap = new HashMap<>(); int method = 2; if (method == 1) { paramsMap.put(1, "method1"); } else if (method == 2) { paramsMap.put(2, "method2"); } System.out.println(paramsMap); // 枚举 Map<Integer, String> paramsMap2 = new HashMap<>(); paramsMap2.put(method, AdviceTypeEnum.fromValue(method).getDisplay()); System.out.println(paramsMap2); ; } }