枚举
提示
枚举
- 枚举是类
- 在编译时,实例是已知的
- 隐式扩展
java.lang.Enum
java
public enum Direction {
NORTH, SOUTH, EAST, WEST
}
class DirectionTest {
public test() {
const Direction direction = Direction.EAST;
if (direction == Direction.EAST) {
// ..
}
}
}
提示
使用 switch
表达式时,编译器会检查是否枚举了所有值,阅读 Accessing, evaluating, and comparing enums。
一些方法
- 枚举可以有构造函数、方法和字段
values()
valueOf()
name()
ordinal()
compareTo()
java
public class Test {
public enum DayOfWeek {
MONDAY("MON"), TUESDAY("TUE"), WEDNESDAY("WED"), THURSDAY("THU"), FRIDAY("FRI"), SATURDAY("SAT"), SUNDAY("SUN");
private final String abbreviation;
DayOfWeek(String abbreviation) {
this.abbreviation = abbreviation;
}
public String getAbbreviation() {
return abbreviation;
}
}
public static void main(String[] args) {
for (DayOfWeek day : DayOfWeek.values()) {
System.out.print(day.getAbbreviation() + " ");
}
// MON TUE WED THU FRI SAT SUN
System.out.println("\n\ngetAbbreviation() 返回值");
System.out.println(DayOfWeek.MONDAY.getAbbreviation());
// MON
System.out.println("\nvalueOf() 返回值");
System.out.println(DayOfWeek.valueOf("MONDAY").getAbbreviation());
// MON
System.out.println("\nname() 返回名称");
System.out.println(DayOfWeek.MONDAY.name());
// MONDAY
System.out.println("\nordinal() 返回索引(出现的顺序)");
System.out.println(DayOfWeek.MONDAY.ordinal());
// 0
System.out.println("\ncompareTo() 返回比较结果");
System.out.println(DayOfWeek.MONDAY.compareTo(DayOfWeek.TUESDAY)); // -1
System.out.println(DayOfWeek.WEDNESDAY.compareTo(DayOfWeek.MONDAY)); // 2
}
}
枚举的单例
利用枚举的特性,确保一个类只有一个实例。
java
public enum Singleton {
INSTANCE;
// some fields, methods, etc.
public void doSomething() {
// ...
}
}
抽象方法
java
enum MyEnum {
A() {
@Override
void doSomething() {
System.out.println("a");
}
},
B() {
@Override
void doSomething() {
System.out.println("b");
}
};
abstract void doSomething();
}