Java 枚舉類(Enum)支持以下操作:
enum
定義一個枚舉類,并為其指定一組有限的常量值。例如:public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Day today = Day.MONDAY;
枚舉實例的默認構造函數(shù):枚舉類自動繼承自 java.lang.Enum
類,該類提供了一個默認的無參構造函數(shù)。但是,你不能顯式地定義一個無參構造函數(shù),因為它會被隱式地使用。
枚舉實例的比較:使用 ==
操作符比較兩個枚舉實例是否相等。因為枚舉實例是單例對象,所以它們在內存中只存在一次。例如:
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()
方法根據(jù)字符串名稱獲取對應的枚舉實例。例如:Day monday = Day.valueOf("MONDAY");
System.out.println("Today is: " + monday);
values()
方法獲取枚舉類中所有定義的枚舉實例,并使用 for-each 循環(huán)遍歷它們。例如: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);