在Java中,枚舉(Enum)是一種特殊的類,用于表示固定數量的常量值
public enum Weekday {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
}
在這個例子中,我們定義了一個名為Weekday
的枚舉類型,它包含7個常量值,分別表示星期一到星期日。
要使用這個枚舉類型,你可以直接引用它的常量值,如下所示:
public class EnumExample {
public static void main(String[] args) {
Weekday today = Weekday.MONDAY;
System.out.println("Today is " + today);
}
}
輸出結果將會是:
Today is MONDAY
此外,枚舉類型還提供了一些內置方法,如values()
和valueOf()
,用于獲取枚舉類型的所有值或根據字符串名稱查找特定值。例如:
public class EnumMethodsExample {
public static void main(String[] args) {
// 獲取所有的Weekday值
Weekday[] weekdays = Weekday.values();
for (Weekday day : weekdays) {
System.out.println(day);
}
// 根據字符串名稱查找Weekday值
Weekday dayByName = Weekday.valueOf("FRIDAY");
System.out.println("Found by name: " + dayByName);
}
}
輸出結果將會是:
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
Found by name: FRIDAY