Java - Enum 枚举

目录

前言

枚举是 Java1.5 引入的新特性,通过关键字 enum 来定义枚举类。


应用

定义

public enum WeekEnum {

    Monday(1, "周一"),
    Tuesday(2, "周二"),
    Wednesday(3, "周三"),
    Thursday(4, "周四"),
    Friday(5, "周五"),
    Saturday(6, "周六"),
    weekend(7, "周天");

    private Integer value;
    private String description;

    WeekEnum(Integer value, String description) {
        this.value = value;
        this.description = description;
    }

    public Integer getValue() {
        return this.value;
    }

    public String getDesc() {
        return this.description;
    }
}
class test {
    public static void main(String[] args) {
        WeekEnum weekEnum = WeekEnum.Friday;

        System.out.println(weekEnum); // Friday
        System.out.println(weekEnum.getValue()); // 5
        System.out.println(weekEnum.getDesc()); // 周五
    }
}

枚举类的switch

  • 错误用法
WeekEnum weekEnum = WeekEnum.Friday;

switch(weekEnum) {
	// An enum switch case label must be the unqualified name of an enumeration constant
   case WeekEnum.Friday:
       break;
   default:
       break;
}
  • 正确用法
WeekEnum weekEnum = WeekEnum.Friday;

switch (weekEnum) {
   case Friday:
       System.out.println(weekEnum);
       break;
   case Saturday:
       break;
}

枚举值向枚举类型转换

public static WeekEnum toWeekEnum(int value) {
    return Stream.of(WeekEnum.values())
                 .filter(item -> item.value == value)
                 .findAny()
                 .orElse(null);
}
public static void main(String[] args) {
    System.out.println(WeekEnum.toWeekEnum(1)); // Monday
}

- End -
梦想是咸鱼
关注一下吧
Java - Enum 枚举
上一篇:P6449 [COCI2008-2009#4] B(洛谷)


下一篇:P1202 [USACO1.1]黑色星期五Friday the Thirteenth