用法一:常量
在JDK1.5 之前,我们定义常量都是: public static fianl…. 。现在好了,有了枚举,可以把相关的常量分组到一个枚举类型里,而且枚举提供了比常量更多的方法。
public enum Color {
RED, GREEN, BLANK, YELLOW
}
用法二:switch
JDK1.6之前的switch语句只支持int,char,enum类型,使用枚举,能让我们的代码可读性更强。
enum Signal {
GREEN, YELLOW, RED
}
public class TrafficLight {
Signal color = Signal.RED;
public void change() {
switch (color) {
case RED:
color = Signal.GREEN;
break;
case YELLOW:
color = Signal.RED;
break;
case GREEN:
color = Signal.YELLOW;
break;
}
}
}
用法三:向枚举中添加属性和方法
主要注意两点:1>必须先定义 enum 实例 2>如果打算自定义自己的方法,那么必须在enum实例序列的最后添加一个分号。
public enum Color {
RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);//分好很重要,不能少
// 成员属性,类似于class中的变量名,这里是属性
private String name;
private int index;
// 构造方法,这是带构造器的方法,与class的方法无异,反编译后可以发现java编译器是把Enum当做Class处理的
private Color(String name, int index) {
this.name = name;
this.index = index;
}
// 普通方法
public static String getName(int index) {
for (Color c : Color.values()) {
if (c.getIndex() == index) {
return c.name;
}
}
return null;
}
// get set 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
用法四:覆盖枚举的方法
下面是Enum的API方法,可以Override
protected Object clone()
抛出 CloneNotSupportedException。
int compareTo(E o)
比较此枚举与指定对象的顺序。
boolean equals(Object other)
当指定对象等于此枚举常量时,返回 true。
protected void finalize()
枚举类不能有 finalize 方法。
Class<E> getDeclaringClass()
返回与此枚举常量的枚举类型相对应的 Class 对象。
int hashCode()
返回枚举常量的哈希码。
String name()
返回此枚举常量的名称,在其枚举声明中对其进行声明。
int ordinal()
返回枚举常量的序数(它在枚举声明中的位置,其中初始常量序数为零)。
String toString()
返回枚举常量的名称,它包含在声明中。
static <T extends Enum<T>> T valueOf(Class<T> enumType, String Name)
返回带指定名称的指定枚举类型的枚举常量。
用法五:EnumSet、EnumMap的使用
// EnumSet的使用
EnumSet<Color > colorSet = EnumSet.allOf(Color.class);
for (Color c : colorSet ) {
System.out.println(c);
}
// EnumMap的使用
EnumMap<Color,String> colorMap = new EnumMap<Color,String>(Color.class);
stateMap.put(Color.RED, "is Red");
stateMap.put(Color.GREEN, "is Green");
for (Color c : Color.values()) {
System.out.println(c.name() + ":" + colorMap.get(c));
}