1. 程式人生 > >JavaSE--枚舉類

JavaSE--枚舉類

pri param where lan protect string targe args orm

參考:http://www.cnblogs.com/hyl8218/p/5088287.html

枚舉類聲明定義的類型是一個類,因此盡量不要構造新對象。

所有枚舉類型都是 java.lang.Enum 類的子類,他們繼承了這個類的許多方法。

枚舉類型的每一個值都將映射到 protected Enum(String name, int ordinal) 構造函數中,在這裏,每個值的名稱都被轉換成一個字符串,並且序數設置表示了此設置被創建的順序。

 1 /**
 2      * Sole constructor.  Programmers cannot invoke this constructor.
3 * It is for use by code emitted by the compiler in response to 4 * enum type declarations. 5 * 6 * @param name - The name of this enum constant, which is the identifier 7 * used to declare it. 8 * @param ordinal - The ordinal of this enumeration constant (its position
9 * in the enum declaration, where the initial constant is assigned 10 * an ordinal of zero). 11 */ 12 protected Enum(String name, int ordinal) { 13 this.name = name; 14 this.ordinal = ordinal; 15 }

toString 方法能夠返回枚舉常量名。

 1  /**
 2      * Returns the name of this enum constant, as contained in the
3 * declaration. This method may be overridden, though it typically 4 * isn‘t necessary or desirable. An enum type should override this 5 * method when a more "programmer-friendly" string form exists. 6 * 7 * @return the name of this enum constant 8 */ 9 public String toString() { 10 return name; 11 }

在比較兩個枚舉類型的值時,永遠不需要調用 equals,而直接使用 ==。

參考:http://blog.csdn.net/x_iya/article/details/53291536

toString 的逆方法是靜態方法 valueOf

 1 public class Size2 {
 2     
 3     public static void main(String[] args) {
 4         A1Size enumEntity = Enum.valueOf(A1Size.class, "SMALL");
 5     }
 6 
 7 }
 8 
 9 enum A1Size {
10     
11     SMALL("S"), MEDIM("M"), LARGER("L"), EXTRA_LARGE("XL");
12 
13     private String abbreviation;
14 
15     private A1Size(String abbreviation) {
16         this.abbreviation = abbreviation;
17     }
18 
19     public String getAbbreviation() {
20         return abbreviation;
21     }
22 
23 }

每個枚舉類型都有一個靜態的 values 方法,他講返回一個包含全部枚舉值得數組。

ordinal 方法返回 enum 聲明中枚舉常量的位置,位置從 0 開始計數。

JavaSE--枚舉類