Java 枚举类(Enum)支持以下操作:
enum
定义一个枚举类,并为其指定一组有限的常量值。例如:public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Day today = Day.MONDAY;
枚举实例的默认构造函数:枚举类自动继承自 java.lang.Enum
类,该类提供了一个默认的无参构造函数。但是,你不能显式地定义一个无参构造函数,因为它会被隐式地使用。
枚举实例的比较:使用 ==
操作符比较两个枚举实例是否相等。因为枚举实例是单例对象,所以它们在内存中只存在一次。例如:
Day today = Day.MONDAY;
Day tomorrow = Day.TUESDAY;
if (today == tomorrow) {
System.out.println("Today is the same as tomorrow.");
} else {
System.out.println("Today is not the same as tomorrow.");
}
ordinal()
方法获取枚举实例在枚举类中的位置(从 0 开始)。例如:int mondayOrdinal = Day.MONDAY.ordinal();
System.out.println("Monday's ordinal value is: " + mondayOrdinal);
name()
方法获取枚举实例的名称(即定义时的常量值)。例如:String mondayName = Day.MONDAY.name();
System.out.println("Monday's name is: " + mondayName);
valueOf()
方法根据字符串名称获取对应的枚举实例。例如:Day monday = Day.valueOf("MONDAY");
System.out.println("Today is: " + monday);
values()
方法获取枚举类中所有定义的枚举实例,并使用 for-each 循环遍历它们。例如:for (Day day : Day.values()) {
System.out.println(day);
}
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
public String getDayOfWeek() {
switch (this) {
case SUNDAY:
return "Sunday";
case MONDAY:
return "Monday";
case TUESDAY:
return "Tuesday";
case WEDNESDAY:
return "Wednesday";
case THURSDAY:
return "Thursday";
case FRIDAY:
return "Friday";
case SATURDAY:
return "Saturday";
default:
throw new IllegalStateException("Unexpected value: " + this);
}
}
}
然后,你可以像这样调用枚举实例的方法:
Day today = Day.MONDAY;
String dayOfWeek = today.getDayOfWeek();
System.out.println("Today is: " + dayOfWeek);