枚举类型(Enumerated type)
关键字enum
例如
//: initialization/Spiciness.java
public enum Spiciness {
NOT, MILD, MEDIUM, HOT, FLAMING
} ///:~
注意枚举类型的实例都是常量(包括NOT,MILD,MEDIUM,HOT,FLAMING)所以按照习惯用大写字母
要使用enum,则要创建该类型的句柄,并将其分配给一个实例
如:
public class SimpleEnumUse {
public static void main(String[] args) {
Spiciness howHot = Spiciness.MEDIUM;
System.out.println(howHot);
}
}
/* Output:
MEDIUM
创建enum时,编译器会自动添加有用的特性,如toString(),ordinal()(枚举常量的序数)和value()(返回按顺序排列的值为enum常量的数组)
如:
//: initialization/EnumOrder.java
public class EnumOrder {
public static void main(String[] args) {
for(Spiciness s : Spiciness.values())
System.out.println(s + ", ordinal " + s.ordinal());
}
}
/* Output:
NOT, ordinal 0
MILD, ordinal 1
MEDIUM, ordinal 2
HOT, ordinal 3
FLAMING, ordinal 4
*///:~
enum是类,有自己的方法
enum常见于switch中,
如下例:
//: initialization/Burrito.java public
class Burrito {
Spiciness degree;
public Burrito(Spiciness degree) {
this.degree = degree;
}
public void describe() {
System.out.print("This burrito is ");
switch(degree) {
case NOT: System.out.println("not spicy at all."); break;
case MILD:
case MEDIUM: System.out.println("a little hot."); break;
case HOT:
case FLAMING:
default: System.out.println("maybe too hot.");
}
}
public static void main(String[] args) {
Burrito plain = new Burrito(Spiciness.NOT),
greenChile = new Burrito(Spiciness.MEDIUM), j
alapeno = new Burrito(Spiciness.HOT);
plain.describe();
greenChile.describe();
jalapeno.describe();
}
}
/* Output:
This burrito is not spicy at all.
This burrito is a little hot.
This burrito is maybe too hot.
*///:~