在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