JavaSE--枚举类

参考: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 开始计数。

原文地址:https://www.cnblogs.com/microcat/p/6940638.html