Java 枚舉(enum)
java 枚舉(enum)
java 枚舉是一個特殊的類,用于表示一組常量。
java 枚舉類使用 enum 關鍵字來定義,各個常量使用逗號 , 來分割。
1. java 枚舉的定義語法
enum-modifiers enum enumname:enum-base { enum-body }
例如定義一個顏色的枚舉類。
enum color { red, green, blue; }
以上枚舉類 color 顏色常量有 red, green, blue,分別表示紅色,綠色,藍色。
2. java 枚舉的使用范例
enum color { red, green, blue; } public class enumtest { // 執(zhí)行輸出結果 public static void main(string[] args) { color c1 = color.red; system.out.println(c1); } }
執(zhí)行以上代碼輸出結果為:
red
3. 內(nèi)部類中使用枚舉
枚舉類也可以聲明在內(nèi)部類中:
public class enumtest { enum color { red, green, blue; } // 執(zhí)行輸出結果 public static void main(string[] args) { color c1 = color.red; system.out.println(c1); } }
執(zhí)行以上代碼輸出結果為:
red
每個枚舉都是通過 class 在內(nèi)部實現(xiàn)的,且所有的枚舉值都是 public static final 的。
以上的枚舉類 color 轉(zhuǎn)化在內(nèi)部類實現(xiàn):
class color { public static final color red = new color(); public static final color blue = new color(); public static final color green = new color(); }
4. 迭代枚舉元素
可以使用 for 語句來迭代枚舉元素:
enum color { red, green, blue; } public class myclass { public static void main(string[] args) { for (color myvar : color.values()) { system.out.println(myvar); } } }
執(zhí)行以上代碼輸出結果為:
red green blue
5. switch 中使用枚舉類
枚舉類常應用于 switch 語句中:
enum color { red, green, blue; } public class myclass { public static void main(string[] args) { color myvar = color.blue; switch(myvar) { case red: system.out.println("紅色"); break; case green: system.out.println("綠色"); break; case blue: system.out.println("藍色"); break; } } }
執(zhí)行以上代碼輸出結果為:
藍色
6. 枚舉類的方法
enum 定義的枚舉類默認繼承了 java.lang.enum 類,并實現(xiàn)了 java.lang.seriablizable 和 java.lang.comparable 兩個接口。
values(), ordinal() 和 valueof() 方法位于 java.lang.enum 類中:
- values() 返回枚舉類中所有的值。
- ordinal()方法可以找到每個枚舉常量的索引,就像數(shù)組索引一樣。
- valueof()方法返回指定字符串值的枚舉常量。
enum color { red, green, blue; } public class enumtest { public static void main(string[] args) { // 調(diào)用 values() color[] arr = color.values(); // 迭代枚舉 for (color col : arr) { // 查看索引 system.out.println(col + " at index " + col.ordinal()); } // 使用 valueof() 返回枚舉常量,不存在的會報錯 illegalargumentexception system.out.println(color.valueof("red")); // system.out.println(color.valueof("white")); } }
執(zhí)行以上代碼輸出結果為:
red at index 0 green at index 1 blue at index 2 red
7. 枚舉類成員
枚舉跟普通類一樣可以用自己的變量、方法和構造函數(shù),構造函數(shù)只能使用 private 訪問修飾符,所以外部無法調(diào)用。枚舉既可以包含具體方法,也可以包含抽象方法。 如果枚舉類具有抽象方法,則枚舉類的每個范例都必須實現(xiàn)它。
enum color { red, green, blue; // 構造函數(shù) private color() { system.out.println("constructor called for : " + this.tostring()); } public void colorinfo() { system.out.println("universal color"); } } public class enumtest { // 輸出 public static void main(string[] args) { color c1 = color.red; system.out.println(c1); c1.colorinfo(); } }
執(zhí)行以上代碼輸出結果為:
constructor called for : red constructor called for : green constructor called for : blue red universal color