掌握类型安全的常量定义与高级应用
枚举(Enum)是Java 5引入的一种特殊的类类型,用于定义一组固定的常量。枚举提供了类型安全的常量定义方式,比传统的常量定义更加安全和易用。
public enum Day {
MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public enum Color {
RED("红色", "#FF0000"),
GREEN("绿色", "#00FF00"),
BLUE("蓝色", "#0000FF");
private final String name;
private final String code;
Color(String name, String code) {
this.name = name;
this.code = code;
}
}
public enum Operation {
PLUS("+") {
public double apply(double x, double y) {
return x + y;
}
},
MINUS("-") {
public double apply(double x, double y) {
return x - y;
}
};
public abstract double apply(double x, double y);
}
Java枚举类型自动继承java.lang.Enum类,提供了一系列有用的内置方法:
方法 | 说明 | 示例 | 返回值 |
---|---|---|---|
name() |
返回枚举常量名称 | Color.RED.name() |
"RED" |
ordinal() |
返回枚举常量序号 | Color.RED.ordinal() |
0 |
toString() |
返回枚举常量字符串表示 | Color.RED.toString() |
"RED" |
valueOf(String) |
根据名称获取枚举常量 | Color.valueOf("RED") |
Color.RED |
values() |
返回所有枚举常量数组 | Color.values() |
[RED, GREEN, BLUE] |
compareTo() |
比较枚举常量顺序 | Color.RED.compareTo(Color.BLUE) |
负数 |
public enum OrderStatus {
PENDING("待处理"),
CONFIRMED("已确认"),
SHIPPED("已发货"),
DELIVERED("已送达"),
CANCELLED("已取消");
private final String description;
OrderStatus(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
public enum LogLevel {
DEBUG(1, "调试"),
INFO(2, "信息"),
WARN(3, "警告"),
ERROR(4, "错误");
private final int level;
private final String description;
LogLevel(int level, String description) {
this.level = level;
this.description = description;
}
public boolean shouldLog(LogLevel targetLevel) {
return this.level >= targetLevel.level;
}
}
public enum DiscountStrategy {
NONE {
public double apply(double price) {
return price;
}
},
STUDENT {
public double apply(double price) {
return price * 0.9; // 9折
}
},
VIP {
public double apply(double price) {
return price * 0.8; // 8折
}
};
public abstract double apply(double price);
}
点击下面的按钮,在在线IDE中查看和运行完整的枚举示例代码:
enum Status { ACTIVE, INACTIVE }
static final int ACTIVE = 1