Java enum实现原理
- 2016-05-18 20:53:00
- admin
- 原创 1287
一、enum实现原理
实际写法:
public enum Color {
GREEN, YELLOW, RED
}
底层实现:
public final class Color extends java.lang.Enum<Color>
public static final Color GREEN;
public static final Color YELLOW;
public static final Color RED;
private static final Color colors[];
static {
GREEN = new Color("GREEN", 0);
YELLOW = new Color("YELLOW", 1);
RED = new Color("RED", 2);
colors = new Color[3];
colors[0] = GREEN;
colors[1] = YELLOW;
colors[2] = RED;
}
public static Color[] values();
public static Color valueOf(java.lang.String);
public int compareTo(Color);
使用说明:
1、枚举有两个重要的参数name名字和ordinal序号,name是变量名,ordinal从0开始递增且不能指定;
2、values方法拷贝colors数组,valueOf方法查找对应枚举,compareTo方法根据序号比较;
3、switch枚举时会先调用ordinal方法;
二、枚举添加成员
示例代码:
public enum Color {
GREEN("green", 1),
YELLOW("yellow", 2),
RED("red", 3);
private Color(String name, int index) {
System.out.println(this.name());
System.out.println(this.ordinal());
}
}
输出结果:
GREEN
0
YELLOW
1
RED
2