Java 枚举类似于类,但主要用于常量。它使用构造函数,就像类一样。我认为了解枚举如何工作的一个好方法是看一个例子。这是我前一段时间学习时自己写的一个小例子。
public class UseEnum {
public enum Colors {
RED("red", 1), BLUE("blue", 2), GREEN("green", 3),
YELLOW("yellow", 4), ORANGE("orange", 5), PURPLE("purple", 6),
PINK("pink", 7), WHITE("white", 8), BLACK("black", 9);
private String color = "";
private int id;
private Colors(String color, int id) {
this.color = color;
this.id = id;
}
private String getColor() {
return color;
}
private int getId() {
return id;
}
}
public static void main(String[] args) {
while(true){ //infinite loop
UseEnum ue = new UseEnum();
ue.findColor(option);
}
}
private static int option;
private UseEnum() {
try{
Scanner s = new Scanner(System.in);
System.out.print("Enter an ID: ");
option = s.nextInt();
}catch(Exception e){
System.out.println("\terror: invalid number");
System.exit(1);
}
}
private void findColor(int id) {
boolean found = false;
if(id == 10)
System.exit(0);
for(Colors c : Colors.values()) {
if(c.getId() == id) {
System.out.println("\t"+c.getColor());
found = true;
break;
}
}
if(found != true)
System.out.println("\tinvalid");
}
}
枚举可以用在 switch 语句中,这使得它们非常有用。
我推荐这篇文章进一步阅读:javarevisited