public class TestEnum { /*最普通的枚舉*/ public enum ColorSelect { red, green, yellow, blue; } /* 枚舉也能夠象通常的類同樣添加方法和屬性,你能夠爲它添加靜態和非靜態的屬性或方法,這一切都象你在通常的類中作的那樣. */ public enum Season { // 枚舉列表必須寫在最前面,不然編譯出錯 winter, spring, summer, fall; private final static String location = "Phoenix"; public static Season getBest() { if (location.equals("Phoenix")) return winter; else return summer; } } /*還能夠有構造方法*/ public enum Temp { /*經過括號賦值,並且必須有帶參構造器和一屬性跟方法,不然編譯出錯 * 賦值必須是都賦值或都不賦值,不能一部分賦值一部分不賦值 * 若是不賦值則不能寫構造器,賦值編譯也出錯*/ absoluteZero(-459), freezing(32),boiling(212), paperBurns(451); private final int value; public int getValue() { return value; } //構造器默認也只能是private, 從而保證構造函數只能在內部使用 Temp(int value) { this.value = value; } } public static void main(String[] args) { /* * 枚舉類型是一種類型,用於定義變量,以限制變量的賦值 賦值時經過"枚舉名.值"來取得相關枚舉中的值 */ ColorSelect m = ColorSelect.blue; switch (m) { /*注意:枚舉重寫了ToString(),說以枚舉變量的值是不帶前綴的 *因此爲blue而非ColorSelect.blue */ case red: System.out.println("color is red"); break; case green: System.out.println("color is green"); break; case yellow: System.out.println("color is yellow"); break; case blue: System.out.println("color is blue"); break; } System.out.println("遍歷ColorSelect中的值"); /*經過values()得到枚舉值的數組*/ for (ColorSelect c : ColorSelect.values()) { System.out.println(c); } System.out.println("枚舉ColorSelect中的值有:"+ColorSelect.values().length+"個"); /*ordinal()返回枚舉值在枚舉中的索引位置,從0開始*/ System.out.println(ColorSelect.red.ordinal());//0 System.out.println(ColorSelect.green.ordinal());//1 System.out.println(ColorSelect.yellow.ordinal());//2 System.out.println(ColorSelect.blue.ordinal());//3 /*枚舉默認實現了java.lang.Comparable接口*/ System.out.println(ColorSelect.red.compareTo(ColorSelect.green)); System.out.println(Season.getBest()); for(Temp t:Temp.values()){ /*經過getValue()取得相關枚舉的值*/ System.out.println(t+"的值是"+t.getValue()); } } }