枚举概述
枚举用来管理一组相关常量的集合,使用枚举可以提高程序的可读性,使代码更清晰且更易于维护。
在 Java 5 之前没有提供枚举类型,可以通过声明静态常量(final static 变量)替代枚举常量。
通常在接口中声明一组静态常量,当然也可以在一般类中声明一组静态常量。这些常量往往都是 int 类型,这是为了以后方便使用 switch 语句进行判断。
public interface WeekDays { // 枚举常量列表 int MONDAY = 0; // 星期一 int TUESDAY = 1; // 星期二 int WEDNESDAY = 2; // 星期三 ... ... }
使用常量的缺点:
- 类型不安全。程序执行过程中很有可能给 day 变量传入一个任意的整数值,可能导致程序出现错误。
- 程序不方便调试。在程序调试时,如果通过日志输出day值,那么只能看到 0~4 之间的数值。
枚举类型可以避免直接使用常量所导致的问题。Java 5 之后可以使用枚举类型了,Java中枚举类型的作用已经不仅仅是定义一组常量提高程序的可读性了,还具有如下特性:
- Java 枚举类型是一种类,是引用类型,具有了面向对象特性,可以添加方法和成员变量等;
- Java 枚举类型继承 java.lang.Enum,且不需要显式声明;
- Java 枚举类型可以实现接口,与类实现接口类似;
- Java 枚举类型不能被继承,不存在子类;
- 枚举类型都实现了Java API中的 Comparable 接口,都可以通过方法compareTo与其他枚举值进行比较。比较其实就是比较 ordinal 的大小;
- 可搭配 switch 语句使用,在 switch 语句内部,枚举值不能带枚举类型前缀。
枚举类声明
[public] enum 枚举名 { 枚举常量列表 }
“枚举名”是该枚举类的名称。它首先应该是有效的标识符,其次应该遵守 Java 命名规范。建议以 Enum 结尾。
枚举类中成员变量和成员方法
枚举类可以像类一样包含成员变量和成员方法,成员变量可以是实例变量也可以是静态变量,成员方法可以是实例方法,也可以是静态方法,但不能是抽象方法。
枚举类构造方法
public enum WeekDayEnum { // 枚举常量列表 MONDAY("星期一", 0), TUESDAY("星期二", 1), WEDNESDAY("星期三", 2), THURSDAY( "星期四", 3), FRIDAY("星期五", 4); // 实例变量 private final String name; private final int index; private WeekDayEnum(String name, int index) { this.name = name; this.index = index; } }
注意枚举类的中的构造方法只能是私有访问级别,构造方法可以省略 private 关键字,但它仍然是私有的构造方法。这也说明了枚举类不允许在外部创建对象。
枚举常用方法
所有枚举类都继承java.lang.Enum类,Enum中定义了一些枚举中常用的方法:
int ordinal()
:返回枚举常量的顺序。每个枚举值经常有一个关联的标识符,为枚举常量声明的顺序,ordinal值会从从数字 0 开始。
枚举类型[] values()
:静态方法,返回一个包含全部枚举常量的数组。
枚举类型 valueOf(String str)
:静态方法,str 是枚举常量对应的字符串,返回一个包含枚举类型实例。
jdk1.8 Enum 的源码
public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable { /** * The name of this enum constant, as declared in the enum declaration. * Most programmers should use the {@link #toString} method rather than * accessing this field. */ private final String name; /** * Returns the name of this enum constant, exactly as declared in its * enum declaration. * * <b>Most programmers should use the {@link #toString} method in * preference to this one, as the toString method may return * a more user-friendly name.</b> This method is designed primarily for * use in specialized situations where correctness depends on getting the * exact name, which will not vary from release to release. * * @return the name of this enum constant */ public final String name() { return name; } /** * The ordinal of this enumeration constant (its position * in the enum declaration, where the initial constant is assigned * an ordinal of zero). * * Most programmers will have no use for this field. It is designed * for use by sophisticated enum-based data structures, such as * {@link java.util.EnumSet} and {@link java.util.EnumMap}. */ private final int ordinal; /** * Returns the ordinal of this enumeration constant (its position * in its enum declaration, where the initial constant is assigned * an ordinal of zero). * * Most programmers will have no use for this method. It is * designed for use by sophisticated enum-based data structures, such * as {@link java.util.EnumSet} and {@link java.util.EnumMap}. * * @return the ordinal of this enumeration constant */ public final int ordinal() { return ordinal; } /** * Sole constructor. Programmers cannot invoke this constructor. * It is for use by code emitted by the compiler in response to * enum type declarations. * * @param name - The name of this enum constant, which is the identifier * used to declare it. * @param ordinal - The ordinal of this enumeration constant (its position * in the enum declaration, where the initial constant is assigned * an ordinal of zero). */ protected Enum(String name, int ordinal) { this.name = name; this.ordinal = ordinal; } /** * Returns the name of this enum constant, as contained in the * declaration. This method may be overridden, though it typically * isn't necessary or desirable. An enum type should override this * method when a more "programmer-friendly" string form exists. * * @return the name of this enum constant */ public String toString() { return name; } /** * Returns true if the specified object is equal to this * enum constant. * * @param other the object to be compared for equality with this object. * @return true if the specified object is equal to this * enum constant. */ public final boolean equals(Object other) { return this==other; } /** * Returns a hash code for this enum constant. * * @return a hash code for this enum constant. */ public final int hashCode() { return super.hashCode(); } /** * Throws CloneNotSupportedException. This guarantees that enums * are never cloned, which is necessary to preserve their "singleton" * status. * * @return (never returns) */ protected final Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } /** * Compares this enum with the specified object for order. Returns a * negative integer, zero, or a positive integer as this object is less * than, equal to, or greater than the specified object. * * Enum constants are only comparable to other enum constants of the * same enum type. The natural order implemented by this * method is the order in which the constants are declared. */ public final int compareTo(E o) { Enum<?> other = (Enum<?>)o; Enum<E> self = this; if (self.getClass() != other.getClass() && // optimization self.getDeclaringClass() != other.getDeclaringClass()) throw new ClassCastException(); return self.ordinal - other.ordinal; } /** * Returns the Class object corresponding to this enum constant's * enum type. Two enum constants e1 and e2 are of the * same enum type if and only if * e1.getDeclaringClass() == e2.getDeclaringClass(). * (The value returned by this method may differ from the one returned * by the {@link Object#getClass} method for enum constants with * constant-specific class bodies.) * * @return the Class object corresponding to this enum constant's * enum type */ @SuppressWarnings("unchecked") public final Class<E> getDeclaringClass() { Class<?> clazz = getClass(); Class<?> zuper = clazz.getSuperclass(); return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper; } /** * Returns the enum constant of the specified enum type with the * specified name. The name must match exactly an identifier used * to declare an enum constant in this type. (Extraneous whitespace * characters are not permitted.) * * <p>Note that for a particular enum type {@code T}, the * implicitly declared {@code public static T valueOf(String)} * method on that enum may be used instead of this method to map * from a name to the corresponding enum constant. All the * constants of an enum type can be obtained by calling the * implicit {@code public static T[] values()} method of that * type. * * @param <T> The enum type whose constant is to be returned * @param enumType the {@code Class} object of the enum type from which * to return a constant * @param name the name of the constant to return * @return the enum constant of the specified enum type with the * specified name * @throws IllegalArgumentException if the specified enum type has * no constant with the specified name, or the specified * class object does not represent an enum type * @throws NullPointerException if {@code enumType} or {@code name} * is null * @since 1.5 */ public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) { T result = enumType.enumConstantDirectory().get(name); if (result != null) return result; if (name == null) throw new NullPointerException("Name is null"); throw new IllegalArgumentException( "No enum constant " + enumType.getCanonicalName() + "." + name); } /** * enum classes cannot have finalize methods. */ protected final void finalize() { } /** * prevent default deserialization */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { throw new InvalidObjectException("can't deserialize enum"); } private void readObjectNoData() throws ObjectStreamException { throw new InvalidObjectException("can't deserialize enum"); } }
参考
- 丁振凡编著,《Java 语言程序设计(第2版)》华东交大版,2014.9