在Java中,枚舉(enum)是一種特殊的數據類型,用于定義一組常量。枚舉常常用于表示一組相關的常量,例如星期幾、月份等。以下是枚舉的一些常見用法:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
isWeekend()
方法來判斷是否是周末:enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
enum Day {
MONDAY("星期一"), TUESDAY("星期二"), WEDNESDAY("星期三"), THURSDAY("星期四"), FRIDAY("星期五"), SATURDAY("星期六"), SUNDAY("星期天");
private String chineseName;
private Day(String chineseName) {
this.chineseName = chineseName;
}
public String getChineseName() {
return chineseName;
}
}
values()
方法來獲取枚舉中所有的常量,并用于遍歷:for (Day day : Day.values()) {
System.out.println(day);
}
Day day = Day.MONDAY;
switch (day) {
case MONDAY:
System.out.println("Today is Monday.");
break;
case TUESDAY:
System.out.println("Today is Tuesday.");
break;
// ...
}
這些只是枚舉的一些常見用法,枚舉還有其他更高級的使用方式,例如枚舉的抽象方法、枚舉的實現接口等。枚舉提供了一種清晰、類型安全的方式來表示一組常量,使代碼更清晰易讀。