Java枚举类型介绍
简单实例:
enum Spiciness{
NOT,MILD,MEDIUM,HOT,FLAMMING
}
public class SimpleEnumUse {
public static void main(String[] args) {
Spiciness howHot = Spiciness.MEDIUM;
System.out.println(howHot);
}
}
枚举类型创建时还会加入一些有用的特性。
比如toString()方法,以及ordinal()方法用于表示某个特定enum常量的声明顺序,static values()方法,用来按照enum常量声明顺序产生这些常量构成的数组。
最好理解enum的方法是将其理解为一个类
switch与enum的结合
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 FLAMMING:
default:
System.out.println("maybe too hot");
}
}
public static void main(String[] args) {
Burrito plain = new Burrito(Spiciness.NOT),
greenChile = new Burrito(Spiciness.MEDIUM),
jalapeno = new Burrito(Spiciness.HOT);
plain.describe();
greenChile.describe();
jalapeno.describe();
}
}