一直以来,都对java的枚举感觉非常的敬仰,一直觉得有些枚举可以get到他的name,还有他的ordinal()返回的东西感觉很神奇的样子,实际上用起来他也带给了我们很多的便利之处.
1.枚举是对象,只要是对象就可以访问他的方法,他的变量,而且他的变量都是静态的变量,可以直接的通过对对象名+.变量名的方式来访问;
2.枚举的equals和等于,还有ordinal方法比对返回结果一致,这个很爽;
3.枚举定义了有限的变量值,方便的来取每个枚举对象中的不同的数据来使用;
4.枚举可以定义方法实现;可以定义抽象方法,抽象方法可以在每个枚举定义时进行事先,实现了之后具体就可以调用这个方法进行相应的逻辑的处理;
我写了一个小的交通信号灯变换的例子,前面的部分是参照的张孝祥老师的视频做的,后面的稍微的实现了一下:
/**
* @author achenbj
* 2014年11月21日 下午4:02:49
*/
package com.cyc;
/**
* @author achenbj
*/
public class EnumTest {
/**
* @param args
*/
public static void main(String[] args) {
WeekDay weekday = WeekDay.FRI;
System.out.println(weekday);
System.out.println(weekday.name() + " ; " + weekday.ordinal());
System.out.println(WeekDay.valueOf("SUN"));
for (WeekDay w : WeekDay.values()) {
System.out.println(w);
}
for (TrafficLamp t : TrafficLamp.values()) {
System.out.println(t + " waiting " + t.time);
System.out.println(t.nextLamp() + " 要量起;");
}
TrafficLamp firstLamp = TrafficLamp.GREEN;
while (true) {
if (TrafficLamp.GREEN == firstLamp) {
System.out.println("You can go, the time left " + firstLamp.time);
try {
Thread.sleep(firstLamp.time * 1000L);
} catch (InterruptedException e) {
System.err.println("等待绿灯时出现了错误!" + e.getMessage());
}
firstLamp = firstLamp.nextLamp();
}
if (TrafficLamp.YELLOW.ordinal() == firstLamp.ordinal()) {
System.out.println("Now the yellow is on , you should wait " + firstLamp.time);
try {
Thread.sleep(firstLamp.time * 1000L);
} catch (InterruptedException e) {
System.err.println("等待黄灯时出现了错误!" + e.getMessage());
}
firstLamp = firstLamp.nextLamp();
}
if (TrafficLamp.RED.equals(firstLamp)) {
System.out.println("Now the RED is on , you should wait " + firstLamp.time);
try {
Thread.sleep(firstLamp.time * 1000L);
} catch (InterruptedException e) {
System.err.println("等待红灯时出现了错误!" + e.getMessage());
}
firstLamp = firstLamp.nextLamp();
}
}
}
public enum WeekDay {
SUN(1), MON(), TUE, WED, THI, FRI, SAT;
private WeekDay() {
System.out.println("First;");
}
private WeekDay(int day) {
System.out.println("Second!");
}
}
/**
* @author achenbj
* 交通灯
*/
public enum TrafficLamp {
RED(3) {
@Override
public TrafficLamp nextLamp() {
return GREEN;
}
},
GREEN(5) {
@Override
public TrafficLamp nextLamp() {
return YELLOW;
}
},
YELLOW(2) {
@Override
public TrafficLamp nextLamp() {
return RED;
}
};
public abstract TrafficLamp nextLamp();
/**
* 每个等中都是有时间的
*/
private int time;
/**
* 带参数的构造方法
*/
private TrafficLamp(int time) {
this.time = time;
}
}
}
以后就不再用静态的常量定义来做了,尽可能的用枚举就行了,枚举真是java5里面很给力的一个功能啊.
感谢sun