特性
- 一种特殊的类
- 默认继承Enum类
- static变量和数组
- final变量(可以==比较)
应用
- 内部类
public class Player {
private PlayerType type;
public enum PlayerType {
TENNIS,
FOOTBALL,
BASKETBALL
}
public boolean isBasketballPlayer() {
return getType() == PlayerType.BASKETBALL;
}
public PlayerType getType() {
return type;
}
public void setType(PlayerType type) {
this.type = type;
}
}
- switch{}case:
switch (playerType) {
case TENNIS:
return "⽹球运动员费德勒";
case FOOTBALL:
return "⾜球运动员C罗";
case BASKETBALL:
return "篮球运动员詹姆斯";
case UNKNOWN:
throw new IllegalArgumentException("未知");
default:
throw new IllegalArgumentException(
"运动员类型: " + playerType);
}
- singleton()
//不能反射(newInstance)和反序列化(Enum类readObject()异常)
public enum EasySingleton{
INSTANCE;
}
扩展:
饿汉(直接实例化)标准、静态代码块、枚举
懒汉(使用实例化)普通、DCL(线程不安全,引入voliate<地址、初始化、引用指向>)、静态内部类
- EnumSet(抽象类)
EnumSet<PlayerType> enumSetNone = EnumSet.noneOf(PlayerType.class);
EnumSet<PlayerType> enumSetAll = EnumSet.allOf(PlayerType.class);
- EnumMap
EnumMap<PlayerType, String> enumMap = new EnumMap<>(PlayerType.class);
put(k,v)、get(k)