在Java中,枚举类型使用enum
关键字来定义。枚举类型可以包含常量、方法和构造函数。以下是枚举类型的一些使用方法:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day day = Day.MONDAY;
System.out.println(day); // 输出 MONDAY
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
values()
方法获取枚举常量数组:Day[] days = Day.values();
for (Day day : days) {
System.out.println(day);
}
valueOf()
方法根据字符串获取枚举常量:Day day = Day.valueOf("MONDAY");
System.out.println(day); // 输出 MONDAY
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