java枚举使用的方法是什么

avatar
作者
筋斗云
阅读量:0

在Java中,枚举类型使用enum关键字来定义。枚举类型可以包含常量、方法和构造函数。以下是枚举类型的一些使用方法:

  1. 定义枚举类型:
public enum Day {     MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } 
  1. 访问枚举常量:
Day day = Day.MONDAY; System.out.println(day); // 输出 MONDAY 
  1. 使用枚举类型中的方法:
public enum Day {     MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;          public boolean isWeekend() {         return this == SATURDAY || this == SUNDAY;     } }  Day day = Day.SATURDAY; System.out.println(day.isWeekend()); // 输出 true 
  1. 使用values()方法获取枚举常量数组:
Day[] days = Day.values(); for (Day day : days) {     System.out.println(day); } 
  1. 使用valueOf()方法根据字符串获取枚举常量:
Day day = Day.valueOf("MONDAY"); System.out.println(day); // 输出 MONDAY 
  1. 实现枚举类型的构造函数和方法:
public enum Day {     MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");          private String displayName;          Day(String displayName) {         this.displayName = displayName;     }          public String getDisplayName() {         return displayName;     } }  Day day = Day.MONDAY; System.out.println(day.getDisplayName()); // 输出 Monday 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!