在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;
// ...
}
这些只是枚举的一些常见用法,枚举还有其他更高级的使用方式,例如枚举的抽象方法、枚举的实现接口等。枚举提供了一种清晰、类型安全的方式来表示一组常量,使代码更清晰易读。