在Java中,枚舉類型使用enum
關(guān)鍵字來定義。枚舉類型可以包含常量、方法和構(gòu)造函數(shù)。以下是枚舉類型的一些使用方法:
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day day = Day.MONDAY;
System.out.println(day); // 輸出 MONDAY
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
Day day = Day.SATURDAY;
System.out.println(day.isWeekend()); // 輸出 true
values()
方法獲取枚舉常量數(shù)組:Day[] days = Day.values();
for (Day day : days) {
System.out.println(day);
}
valueOf()
方法根據(jù)字符串獲取枚舉常量:Day day = Day.valueOf("MONDAY");
System.out.println(day); // 輸出 MONDAY
public enum Day {
MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"), THURSDAY("Thursday"), FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
private String displayName;
Day(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
}
Day day = Day.MONDAY;
System.out.println(day.getDisplayName()); // 輸出 Monday