public enum Color {
RED, YELLOW, BLUE;
}

说明

方法

values()

for (Color color : Color.values()) {
// 下标
System.out.println(color.ordinal());
// 枚举变量名字
System.out.println(color.name());
// 同上
System.out.println(color.toString());
}
// 比较的是下标
System.out.println(Color.valueOf("YELLOW").compareTo(Color.valueOf("BLUE")));

valueOf(String name)

public enum Weekday {
MON(1),TUS(2),WED(3),THU(4),FRI(5),SAT(6),SUN(0); private int index; private Weekday(int index){
this.index = index;
}
}

说明

枚举类中的抽象类

实例:

public enum Color {
RED() {
@Override
public Color getNextColor() {
return YELLOW;
}
},
YELLOW(){
@Override
public Color getNextColor() {
return BLUE;
}
},
BLUE(){
@Override
public Color getNextColor() {
return RED;
}
}; /**
* 获取下一种颜色
* @return
*/
public abstract Color getNextColor();
}
Color yellow = Color.valueOf("YELLOW");
System.out.println(yellow.getNextColor()); // BLUE

枚举类的原理:

public enum Weekday {
MON(1),TUS(2),WED(3),THU(4),FRI(5),SAT(6),SUN(0); private int index; private Weekday(int index){
this.index = index;
}
}

javap 反编译 Weekday.class

public final class enums.Weekday extends java.lang.Enum<enums.Weekday> {
public static final enums.Weekday MON;
public static final enums.Weekday TUS;
public static final enums.Weekday WED;
public static final enums.Weekday THU;
public static final enums.Weekday FRI;
public static final enums.Weekday SAT;
public static final enums.Weekday SUN;
public static enums.Weekday[] values();
public static enums.Weekday valueOf(java.lang.String);
static {};
}

在Color枚举类中定义的 RED、、、本身是一个 Color对象的引用。Color RED = new Color(); 使用匿名内部类方式:

Color RED = new Color() {
@override
public Color getNextColor() {
return YELLOW;
}
}
在枚举类中 只用写 RED(){...} JVM会完成其它操作

枚举类在switch中应用

switch (color) {
case RED:
color = Color.GREEN;
break;
case YELLOW:
color = Color.RED;
break;
case GREEN:
color = Color.YELLOW;
break;
}

枚举类实现接口

public interface Behaviour {
void print();
String getInfo();
}
public enum Weekday implements Behaviour{
MON(1),TUS(2),WED(3),THU(4),FRI(5),SAT(6),SUN(0); private int index; Weekday(int index){
this.index = index;
} @Override
public void print() {
System.out.println(this.index + ":" + toString());
} @Override
public String getInfo() {
return toString();
}
}

枚举实现 单例模式

public enum DataSourceEnum {
DATASOURCE;
private DBConnection connection = null;
private DataSourceEnum() {
connection = new DBConnection();
}
public DBConnection getConnection() {
return connection;
}
}
05-28 15:11