枚舉概述
枚舉用來管理一組相關(guān)常量的集合,使用枚舉可以提高程序的可讀性,使代碼更清晰且更易于維護(hù)。
在 Java 5 之前沒有提供枚舉類型,可以通過聲明靜態(tài)常量(final static 變量)替代枚舉常量。
通常在接口中聲明一組靜態(tài)常量,當(dāng)然也可以在一般類中聲明一組靜態(tài)常量。這些常量往往都是 int 類型,這是為了以后方便使用 switch 語句進(jìn)行判斷。
public interface WeekDays {
// 枚舉常量列表
int MONDAY = 0; // 星期一
int TUESDAY = 1; // 星期二
int WEDNESDAY = 2; // 星期三
... ...
}
使用常量的缺點(diǎn):
- 類型不安全。程序執(zhí)行過程中很有可能給 day 變量傳入一個(gè)任意的整數(shù)值,可能導(dǎo)致程序出現(xiàn)錯(cuò)誤。
- 程序不方便調(diào)試。在程序調(diào)試時(shí),如果通過日志輸出day值,那么只能看到 0~4 之間的數(shù)值。
枚舉類型可以避免直接使用常量所導(dǎo)致的問題。Java 5 之后可以使用枚舉類型了,Java中枚舉類型的作用已經(jīng)不僅僅是定義一組常量提高程序的可讀性了,還具有如下特性:
- Java 枚舉類型是一種類,是引用類型,具有了面向?qū)ο筇匦裕梢蕴砑臃椒ê统蓡T變量等;
- Java 枚舉類型繼承 java.lang.Enum,且不需要顯式聲明;
- Java 枚舉類型可以實(shí)現(xiàn)接口,與類實(shí)現(xiàn)接口類似;
- Java 枚舉類型不能被繼承,不存在子類;
- 枚舉類型都實(shí)現(xiàn)了Java API中的 Comparable 接口,都可以通過方法compareTo與其他枚舉值進(jìn)行比較。比較其實(shí)就是比較 ordinal 的大??;
- 可搭配 switch 語句使用,在 switch 語句內(nèi)部,枚舉值不能帶枚舉類型前綴。
枚舉類聲明
[public] enum 枚舉名 {
枚舉常量列表
}
“枚舉名”是該枚舉類的名稱。它首先應(yīng)該是有效的標(biāo)識(shí)符,其次應(yīng)該遵守 Java 命名規(guī)范。建議以 Enum 結(jié)尾。
枚舉類中成員變量和成員方法
枚舉類可以像類一樣包含成員變量和成員方法,成員變量可以是實(shí)例變量也可以是靜態(tài)變量,成員方法可以是實(shí)例方法,也可以是靜態(tài)方法,但不能是抽象方法。
枚舉類構(gòu)造方法
public enum WeekDayEnum {
// 枚舉常量列表
MONDAY("星期一", 0), TUESDAY("星期二", 1), WEDNESDAY("星期三", 2), THURSDAY(
"星期四", 3), FRIDAY("星期五", 4);
// 實(shí)例變量
private final String name;
private final int index;
private WeekDayEnum(String name, int index) {
this.name = name;
this.index = index;
}
}
注意枚舉類的中的構(gòu)造方法只能是私有訪問級(jí)別,構(gòu)造方法可以省略 private 關(guān)鍵字,但它仍然是私有的構(gòu)造方法。這也說明了枚舉類不允許在外部創(chuàng)建對(duì)象。
枚舉常用方法
所有枚舉類都繼承java.lang.Enum類,Enum中定義了一些枚舉中常用的方法:
-
int ordinal():返回枚舉常量的順序。每個(gè)枚舉值經(jīng)常有一個(gè)關(guān)聯(lián)的標(biāo)識(shí)符,為枚舉常量聲明的順序,ordinal值會(huì)從從數(shù)字 0 開始。 -
枚舉類型[] values():靜態(tài)方法,返回一個(gè)包含全部枚舉常量的數(shù)組。 -
枚舉類型 valueOf(String str):靜態(tài)方法,str 是枚舉常量對(duì)應(yīng)的字符串,返回一個(gè)包含枚舉類型實(shí)例。
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 語言程序設(shè)計(jì)(第2版)》華東交大版,2014.9
- Java 編程的邏輯-微信讀書
https://weread.qq.com/web/reader/b51320f05e159eb51b29226kc81322c012c81e728d9d180