Java教程

Java - Enum 枚举

本文主要是介绍Java - Enum 枚举,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录
  • 前言
  • 应用
    • 定义
    • 枚举类的switch
    • 枚举值向枚举类型转换

前言

枚举是 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 枚举的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!