引言:什么是枚举?
枚举(Enum)是Java中一种特殊的类,用于定义固定数量的常量。枚举让代码更清晰、更安全。
枚举类比
枚举就像一周的星期几:
├── 固定数量:7天
├── 每天有特定含义:星期一、星期二...
├── 不能随意创建新的一天
└── 取值只能是这7天之一
用枚举表示:
enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
为什么使用枚举?
类型安全:枚举值有固定类型,不会出现随意值
代码清晰:用有意义的名称代替魔法数字
编译时检查:减少运行时错误
内置方法:自动获得常用方法
枚举的基本使用
定义枚举
public enum Weekday {
MONDAY, // 星期一
TUESDAY, // 星期二
WEDNESDAY, // 星期三
THURSDAY, // 星期四
FRIDAY, // 星期五
SATURDAY, // 星期六
SUNDAY // 星期日
}
使用枚举
Weekday today = Weekday.FRIDAY;
if (today == Weekday.FRIDAY) {
System.out.println("今天是周五,明天就是周末了!");
}
// switch语句中使用枚举
switch (today) {
case MONDAY:
System.out.println("周一加油!");
break;
case FRIDAY:
System.out.println("周五快乐!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("周末愉快!");
break;
default:
System.out.println("工作日努力!");
}
枚举的常用方法
values() - 获取所有枚举值
Weekday[] days = Weekday.values();
for (Weekday day : days) {
System.out.println(day);
}
valueOf() - 根据名称获取枚举值
Weekday day = Weekday.valueOf("FRIDAY");
System.out.println(day); // FRIDAY
ordinal() - 获取枚举的序号
int index = Weekday.MONDAY.ordinal();
System.out.println("Monday的序号: " + index); // 0
int index2 = Weekday.FRIDAY.ordinal();
System.out.println("Friday的序号: " + index2); // 4
name() - 获取枚举名称
String name = Weekday.MONDAY.name();
System.out.println(name); // MONDAY
带属性的枚举
定义带属性的枚举
public enum Season {
SPRING("春天", "春暖花开"),
SUMMER("夏天", "炎热酷暑"),
AUTUMN("秋天", "秋高气爽"),
WINTER("冬天", "寒冷刺骨");
private final String chineseName;
private final String description;
Season(String chineseName, String description) {
this.chineseName = chineseName;
this.description = description;
}
public String getChineseName() {
return chineseName;
}
public String getDescription() {
return description;
}
}
使用带属性的枚举
Season currentSeason = Season.SPRING;
System.out.println("中文名: " + currentSeason.getChineseName());
System.out.println("描述: " + currentSeason.getDescription());
带方法的枚举
public enum Operation {
PLUS("+") {
@Override
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
@Override
public double apply(double x, double y) {
return x - y;
}
},
MULTIPLY("*") {
@Override
public double apply(double x, double y) {
return x * y;
}
},
DIVIDE("/") {
@Override
public double apply(double x, double y) {
if (y == 0) {
throw new ArithmeticException("除数不能为0");
}
return x / y;
}
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
public String getSymbol() {
return symbol;
}
public abstract double apply(double x, double y);
}
// 使用
double result = Operation.PLUS.apply(10, 5);
System.out.println("10 + 5 = " + result); // 15
枚举实现接口
interface Describable {
String getDescription();
}
public enum Color implements Describable {
RED("红色") {
@Override
public String getDescription() {
return "这是红色";
}
},
GREEN("绿色") {
@Override
public String getDescription() {
return "这是绿色";
}
},
BLUE("蓝色") {
@Override
public String getDescription() {
return "这是蓝色";
}
};
private final String chineseName;
Color(String chineseName) {
this.chineseName = chineseName;
}
public String getChineseName() {
return chineseName;
}
}
// 使用
Color color = Color.RED;
System.out.println(color.getChineseName());
System.out.println(color.getDescription());
枚举在switch中的应用
public enum TrafficLight {
RED, YELLOW, GREEN;
}
TrafficLight light = TrafficLight.GREEN;
switch (light) {
case RED:
System.out.println("红灯停");
break;
case YELLOW:
System.out.println("黄灯等一等");
break;
case GREEN:
System.out.println("绿灯行");
break;
}
枚举的构造方法
私有构造方法
枚举的构造方法自动私有,不能直接调用构造方法创建枚举实例。
public enum Status {
SUCCESS("成功", 200),
ERROR("错误", 500),
NOT_FOUND("未找到", 404);
private final String description;
private final int code;
Status(String description, int code) {
this.description = description;
this.code = code;
}
public String getDescription() {
return description;
}
public int getCode() {
return code;
}
}
// 使用
System.out.println(Status.SUCCESS.getDescription()); // 成功
System.out.println(Status.SUCCESS.getCode()); // 200
小结
- 枚举是固定常量集合,使用enum关键字定义
- 枚举类型安全,取值只能是预定义的值之一
- 枚举自动继承java.lang.Enum类
- 常用方法:values()、valueOf()、ordinal()、name()
- 枚举可以带属性、带方法、实现接口
- 枚举构造方法自动私有
☕ Java 在线代码编辑器
📝 运行结果