Java实现enum
什么是枚举(enum)?
枚举(enum)是一种特殊的类,用于表示一组固定的常量,在Java中,枚举类型使用关键字enum定义,枚举类型的每个实例都是该类型的一个常量,这些常量的名称是唯一的,枚举类型可以包含构造函数、方法和字段,以及实现接口和继承其他类。
如何创建枚举类型?
1、使用关键字enum定义枚举类型
public enum Color { RED, GREEN, BLUE; }
2、定义带有构造函数的枚举类型
public enum Weekday { MONDAY("星期一"), TUESDAY("星期二"), WEDNESDAY("星期三"), THURSDAY("星期四"), FRIDAY("星期五"), SATURDAY("星期六"), SUNDAY("星期日"); private String description; Weekday(String description) { this.description = description; } public String getDescription() { return description; } }
3、定义带有字段和方法的枚举类型
public enum Operation { PLUS("+", (a, b) -> a + b), MINUS("-", (a, b) -> a b), TIMES("*", (a, b) -> a * b), SLASH("/", (a, b) -> a / b); private String symbol; private BiFunction<Integer, Integer, Integer> function; Operation(String symbol, BiFunction<Integer, Integer, Integer> function) { this.symbol = symbol; this.function = function; } public String getSymbol() { return symbol; } public int apply(int a, int b) { return function.apply(a, b); } }
如何使用枚举类型?
1、直接引用枚举常量
Color color = Color.RED;
2、通过枚举常量的名称获取枚举常量实例
Color color = Color.valueOf("RED"); // 或者 Color.RED; 因为已经定义了静态常量final Map<String, Color> CONSTANTS = new HashMap<>(); CONSTANTS.put("RED", Color.RED); Color color = CONSTANTS.get("RED"); // 或者直接使用color = Color.RED; if (color != null) System.out.println(color); else System.out.println("未找到对应的枚举常量"); // 或者直接使用EnumSet<Color> colors = EnumSet.of(Color.RED); if (colors.contains(Color.RED)) System.out.println("找到了对应的枚举常量"); else System.out.println("未找到对应的枚举常量"); // 或者直接使用if (color == Color.RED) System.out.println("找到了对应的枚举常量"); else System.out.println("未找到对应的枚举常量"); ```
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/234874.html