Java枚举类可以通过以下步骤使用:
enum
关键字声明一个枚举类,并在其中定义枚举常量。例如:public enum DayOfWeek {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
DayOfWeek day = DayOfWeek.MONDAY;
System.out.println(day); // 输出: MONDAY
public enum DayOfWeek {
// ...
public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}
DayOfWeek day = DayOfWeek.SATURDAY;
System.out.println(day.isWeekend()); // 输出: true
public enum DayOfWeek {
// ...
public static DayOfWeek fromString(String dayStr) {
for (DayOfWeek day : DayOfWeek.values()) {
if (day.name().equalsIgnoreCase(dayStr)) {
return day;
}
}
throw new IllegalArgumentException("Invalid day of week: " + dayStr);
}
}
DayOfWeek day = DayOfWeek.fromString("monday");
System.out.println(day); // 输出: MONDAY
这些是使用Java枚举类的基本步骤,可以根据需要进行扩展和定制。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: java中如何将字符串转换成int