Enum,枚举常量,由编译程序具体生成,非常有用。
一、使用方法
public enum TrafficLight {
RED,YELLOW,GREEN
}
//等同于调用
new Enum<TrafficLight>("RED",0);
new Enum<TrafficLight>("YELLOW",1);
new Enum<TrafficLight>("GREEN",2);
- 枚举类型符合通用模式 Class Enum<E extends Enum<E>>,而 E 表示枚举类型的名称。枚举类型的每一个值都将映射到 protected Enum(String name, int ordinal) 构造函数中,在这里,每个值的名称都被转换成一个字符串,并且序数设置表示了此设置被创建的顺序;
二、遍历和switch
public static void main(String[] args) {
for(TrafficLight tl : TrafficLight.values()){
System.out.println(tl);
}
TrafficLight light = TrafficLight.RED;
switch (light) {
case RED:
System.out.println("当前是红灯");
break;
case YELLOW:
System.out.println("当前是黄灯");
break;
case GREEN:
System.out.println("当前是绿灯");
break;
default:
break;
}
}
//打印结果
RED
YELLOW
GREEN
当前是红灯
三、自定义属性和方法
public enum TrafficLight {
RED("红灯"),YELLOW("黄灯"),GREEN("绿灯");
private String value;
private TrafficLight(String value){
this.value = value;
}
public String getValue(){
return this.value;
}
@Override
public String toString() {
return this.name()+"_"+this.value;
}
}
//遍历打印(调用toString方法)的结果为:
RED_红灯
YELLOW_黄灯
GREEN_绿灯
四、EnumSet和EnumMap的使用
public static void main(String[] args) {
//EnumSet的使用
EnumSet<TrafficLight> es = EnumSet.allOf(TrafficLight.class);
Iterator<TrafficLight> itSet = es.iterator();
while(itSet.hasNext()){
TrafficLight tl = itSet.next();
System.out.println(tl);
}
//EnumMap的使用
EnumMap<TrafficLight,String> em = new EnumMap<TrafficLight,String>(TrafficLight.class);
em.put(TrafficLight.RED, "红灯");
em.put(TrafficLight.YELLOW, "黄灯");
em.put(TrafficLight.GREEN, "绿灯");
Set<Map.Entry<TrafficLight,String>> set = em.entrySet();
Iterator<Map.Entry<TrafficLight, String>> itMap = set.iterator();
while(itMap.hasNext()){
Entry<TrafficLight, String> entry = itMap.next();
System.out.println(entry.getKey()+"_"+entry.getValue());
}
}
五、实现接口
public interface ShinningTime {
void time();
}
public enum TrafficLight implements ShinningTime{
RED("红灯",60),YELLOW("黄灯",30),GREEN("绿灯",40);
private String value;
private int time;
private TrafficLight(String value,int time){
this.value = value;
this.time = time;
}
public String getValue(){
return this.value;
}
@Override
public String toString() {
return this.name()+"_"+this.value;
}
@Override
public void time() {
System.out.println("The shinning time is :"+time);
}
}
- 所有枚举类均继承自java.lang.Enum,Java不支持多继承,可以通过多接口实现多继承;