目录
EnumMap分发、二维数组分发(简单但是容易出错,不安全),这里不做讲解了
1.如何用
enum Shrubbery { GROUND, CRAWLING, HANGING }
public class EnumClass {
public static void main(String[] args) {
for(Shrubbery s : Shrubbery.values()) {
print(s + " ordinal: " + s.ordinal());
printnb(s.compareTo(Shrubbery.CRAWLING) + " ");
printnb(s.equals(Shrubbery.CRAWLING) + " ");
print(s == Shrubbery.CRAWLING);
print(s.getDeclaringClass());
print(s.name());
print("----------------------");
}
// Produce an enum value from a string name:
for(String s : "HANGING CRAWLING GROUND".split(" ")) {
Shrubbery shrub = Enum.valueOf(Shrubbery.class, s);
print(shrub);
}
}
} /* Output:
GROUND ordinal: 0
-1 false false
class Shrubbery
GROUND
----------------------
CRAWLING ordinal: 1
0 true true
class Shrubbery
CRAWLING
----------------------
HANGING ordinal: 2
1 false false
class Shrubbery
HANGING
----------------------
HANGING
CRAWLING
GROUND
*///:~
上述例子中基本是enum的一个方法不细讲,同时可以直接静态调用如Shrubbery.GROUND。
2.向enum添加方法
enum除了不能继承之外,可以把其看做是一个正常的类。所以可以为其添加方法
public enum OzWitch {
// Instances must be defined first, before methods:
WEST("A"),
private String description;
// Constructor must be package or private access:
private OzWitch(String description) {
this.description = description;
}
public String getDescription() { return description; }
public static void main(String[] args) {
for(OzWitch witch : OzWitch.values())
print(witch + ": " + witch.getDescription());
}
} /* Output:
WEST: A
*///:~
也可以覆盖方法,下面覆盖上面例子toString()方法
public enum OzWitch {
// Instances must be defined first, before methods:
WEST("A"),
private String description;
// Constructor must be package or private access:
private OzWitch(String description) {
this.description = description;
}
@Override
public String toString() {
return "aaaaa";
}
public String getDescription() { return description; }
public static void main(String[] args) {
for(OzWitch witch : OzWitch.values())
print(witch + ": " + witch.getDescription());
}
} /* Output:
WEST: aaaaa
*///:~
3.switch中使用enum
enum Signal { GREEN, YELLOW, RED, }
public class TrafficLight {
Signal color = Signal.RED;
public void change() {
switch(color) {
// Note that you don't have to say Signal.RED
// in the case statement:
case RED: color = Signal.GREEN;
break;
c