枚舉類型
最近在程序裏用到了枚舉類型處理異常的返回值,和異常code挺方便,推薦大家使用枚舉類型
enum Other { ONE,TWO,TREE_BOOK }
由於枚舉類型的實例是常量,因此按照命名慣例他們都用大寫表示,如果在一個名字中有多個單詞,用下劃線將它們隔開。
public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); Other other = Other.TREE_BOOK; System.out.println(other); } } enum Other { ONE,TWO,TREE_BOOK }
在你創建enum時,編譯器會自動添加一些有用的特性,例如,它會創建toString()方法,以便你可以很方便的顯示某個enum的實例(相當於對象,不是成員變量)的名字,ordinal()方法用來表示某個特定enum常量的聲明順序,以及static value()方法,用來按照enum常量的聲明順序,產生由這些常量構成的數組。
public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); for(Other s:Other.values()){ System.out.println(s+"順序號"+s.ordinal()); } } } enum Other { ONE,TWO,TREE_BOOK }
可以將enum當做其他任何類來處理,事實上,enum確實是類,並且具有自己的方法。
public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); Other other = Other.ONE; switch (other){ case ONE: System.out.println("1"); break; case TWO: System.out.println("2"); break; case TREE_BOOK: System.out.println("3"); break; default: System.out.println("輸入不正確"); } } } enum Other { ONE,TWO,TREE_BOOK }
其實default 有沒有都行,要是輸入值不對,編譯器不通過
由於switch是要在有限的可能值集合中進行選擇,因此它與enum正式絕佳的組合。
enum Coffeesize3 { BIG(8),HIGE(10),OVERWHELMING(16); Coffeesize3(int ounces) { this.ounces = ounces; } private int ounces; }
枚舉類型可以有構造器,其中的8.10,16是構造器參數,不是順序號
public class EurekaApplication { Coffeesize3 size; public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); EurekaApplication drink = new EurekaApplication(); drink.size = Coffeesize3.BIG; System.out.println(drink+", ounces:"+drink.size.getOunces()); } } enum Coffeesize3 { BIG(8),HIGE(10),OVERWHELMING(16); Coffeesize3(int ounces) { this.ounces = ounces; } private int ounces; public int getOunces(){ return ounces; } }
輸出