Java 枚舉類的使用方法如下:
enum
定義枚舉類,枚舉值以逗號分隔,并以分號結束。例如:public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Weekday day = Weekday.MONDAY;
name()
方法獲取枚舉值的名稱:String name = day.name(); // 返回 "MONDAY"
==
運算符比較枚舉值。例如:if (day == Weekday.MONDAY) {
// 執行某些操作
}
public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
Weekday day = Weekday.SATURDAY;
boolean isWeekend = day.isWeekend(); // 返回 true
枚舉類還支持其他一些特性,例如可以在枚舉值上定義字段和構造函數,以及實現接口等。