在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