Java枚舉類可以通過以下步驟使用:
enum
關鍵字聲明一個枚舉類,并在其中定義枚舉常量。例如:public enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
DayOfWeek day = DayOfWeek.MONDAY;
System.out.println(day); // 輸出: MONDAY
public enum DayOfWeek {
// ...
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
DayOfWeek day = DayOfWeek.SATURDAY;
System.out.println(day.isWeekend()); // 輸出: true
public enum DayOfWeek {
// ...
public static DayOfWeek fromString(String dayStr) {
for (DayOfWeek day : DayOfWeek.values()) {
if (day.name().equalsIgnoreCase(dayStr)) {
return day;
}
}
throw new IllegalArgumentException("Invalid day of week: " + dayStr);
}
}
DayOfWeek day = DayOfWeek.fromString("monday");
System.out.println(day); // 輸出: MONDAY
這些是使用Java枚舉類的基本步驟,可以根據需要進行擴展和定制。