您的位置:首页 > 编程语言 > Java开发

简单了解Java枚举类型 —— From Thinking In Java(Fourth Eition)

2016-07-18 14:31 519 查看
在Java SE5中添加了enum关键字,即枚举类型。

枚举类型的实例是常量,按照命名习惯它们都应该大写。

public enum Spiciness {
NOT, MILD, MEDIUM, HOT, FLAMING,
}


创建enum时,编译器会自动添加一些有用的特性。例如toString()方法可以方便的显示enum实例的名字;ordinal()方法,用来表示某个特定enum常量的声明顺序;static values()方法,用来按照enum常量的声明顺序,产生由这些常量值构成的数组。

public class EnumOrder {

public static void main(String[] args) {
// TODO Auto-generated method stub
for(Spiciness s : Spiciness.values())
System.out.println(s + " Ordianl: " + s.ordinal());
}

}


enum有一个特别实用的特性,即它可以在switch中使用:

public class EnumInSwitch {
Spiciness degree;
public EnumInSwitch(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 litte hot.");break;
case HOT:
case FLAMING:
default: System.out.println("maybe too hot.");
}
}

public static void main(String[] args) {
// TODO Auto-generated method stub
EnumInSwitch
not = new EnumInSwitch(Spiciness.NOT),
medium = new EnumInSwitch(Spiciness.MEDIUM),
hot = new EnumInSwitch(Spiciness.HOT);
not.describe();
medium.describe();
hot.describe();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: