09. 枚举类

枚举概述

枚举用来管理一组相关常量的集合,使用枚举可以提高程序的可读性,使代码更清晰且更易于维护。

在 Java 5 之前没有提供枚举类型,可以通过声明静态常量(final static 变量)替代枚举常量。
通常在接口中声明一组静态常量,当然也可以在一般类中声明一组静态常量。这些常量往往都是 int 类型,这是为了以后方便使用 switch 语句进行判断。

1
2
3
4
5
6
7
public interface WeekDays {
// 枚举常量列表
int MONDAY = 0; // 星期一
int TUESDAY = 1; // 星期二
int WEDNESDAY = 2; // 星期三
... ...
}

使用常量的缺点:

  1. 类型不安全。程序执行过程中很有可能给 day 变量传入一个任意的整数值,可能导致程序出现错误。
  2. 程序不方便调试。在程序调试时,如果通过日志输出 day 值,那么只能看到 0~4 之间的数值。

枚举类型可以避免直接使用常量所导致的问题。Java 5 之后可以使用枚举类型了,Java 中枚举类型的作用已经不仅仅是定义一组常量提高程序的可读性了,还具有如下特性:

  1. Java 枚举类型是一种类,是引用类型,具有了面向对象特性,可以添加方法和成员变量等;
  2. Java 枚举类型继承 java.lang.Enum,且不需要显式声明;
  3. Java 枚举类型可以实现接口,与类实现接口类似;
  4. Java 枚举类型不能被继承,不存在子类;
  5. 枚举类型都实现了 Java API中的 Comparable 接口,都可以通过方法 compareTo 与其他枚举值进行比较。比较其实就是比较 ordinal 的大小;
  6. 可搭配 switch 语句使用,在 switch 语句内部,枚举值不能带枚举类型前缀。

枚举类声明

1
2
3
[public] enum 枚举名 {
枚举常量列表
}

“枚举名”是该枚举类的名称。它首先应该是有效的标识符,其次应该遵守 Java 命名规范。建议以 Enum 结尾。

枚举类中成员变量和成员方法

枚举类可以像类一样包含成员变量和成员方法,成员变量可以是实例变量也可以是静态变量,成员方法可以是实例方法,也可以是静态方法,但不能是抽象方法。

枚举类构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 是枚举常量对应的字符串,返回一个包含枚举类型实例。
  • public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) Enum 的静态方法,也是返回一个包含枚举类型实例。注意,对于特定的枚举类型 T,可以使用该枚举上隐式声明的公共静态 T valueOf (String)方法来代替此方法,从名称映射到相应的枚举常量。枚举类型的所有常量都可以通过调用该类型的隐式公共静态 T [] value ()方法来获得。

jdk 1.8 Enum 的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
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");
}
}

参考