趣談Java枚舉類

趣談不是瞎談,戲說不是胡說
說到這里我就想到下半年中美合拍的西游記

咳咳,哎?哎?
不好意思跑偏了,下面切入正題

枚舉類到底是什么?
引用維基百科的說明:在數(shù)學(xué)和計算機科學(xué)理論中,一個集的枚舉是列出某些有窮序列集的所有成員的程序,或者是一種特定類型對象的計數(shù)。這兩種類型經(jīng)常(但不總是)重疊。
枚舉是一個被命名的整型常數(shù)的集合,枚舉在日常生活中很常見,例如表示星期的SUNDAY、MONDAY、TUESDAY、WEDNESDAY、THURSDAY、FRIDAY、SATURDAY就是一個枚舉。

Java用一種特殊的數(shù)據(jù)類型幫我們實現(xiàn)了這種理論,那就是枚舉類。

Java中的枚舉類如何定義

public enum OrderStatus {

    NEW("新建",1),
    FINISHED("完成",2);

    private final String name;
    private final int code;

    OrderStatus(String name, int code) {
        this.name = name;
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public int getCode() {
        return code;
    }
}

為什么要用枚舉類
這里引用《Java編程思想》里的一句話:有時恰恰因為它,你才能夠‘優(yōu)雅而干凈’地解決問題。

....
// 更改訂單狀態(tài)
order.setStatus(2);
// 更新數(shù)據(jù)庫
update(order);
....

看到這樣的代碼,你第一時間很煩躁還得去找,我xx知道你寫的是啥,敢不敢告訴我改的狀態(tài)是啥,但是如果把代碼改成這樣

....
// 更改訂單狀態(tài)
order.setStatus(OrderStatus.FINISHED.getCode());
// 更新數(shù)據(jù)庫
update(order);
....

哦,這應(yīng)該是完成狀態(tài)把(猜測)

枚舉類的本質(zhì)是什么
我們將上面的OrderStatus類編譯生成的class文件再用jad反編譯得到OrderStatus.jad

jad OrderStatus.class // OrderStatus.jad
public final class OrderStatus extends Enum
{

    public static OrderStatus[] values()
    {
        return (OrderStatus[])$VALUES.clone();
    }

    public static OrderStatus valueOf(String name)
    {
        return (OrderStatus)Enum.valueOf(com/example/demo/OrderStatus, name);
    }

    private OrderStatus(String s, int i, String name, int code)
    {
        super(s, i);
        this.name = name;
        this.code = code;
    }

    public String getName()
    {
        return name;
    }

    public int getCode()
    {
        return code;
    }

    public static final OrderStatus NEW;
    public static final OrderStatus FINISHED;
    private final String name;
    private final int code;
    private static final OrderStatus $VALUES[];

    static 
    {
        NEW = new OrderStatus("NEW", 0, "\u65B0\u5EFA", 1);
        FINISHED = new OrderStatus("FINISHED", 1, "\u5B8C\u6210", 2);
        $VALUES = (new OrderStatus[] {
            NEW, FINISHED
        });
    }
}

通過反編譯的jad文件可以看出以下幾點
1.enum實際也是一種類
2.類被final修飾不可被繼承
3.繼承Enum類,不可再繼承其他類
4.每一個枚舉實例都會實例化一個OrderStatus對象
5.枚舉實例存儲在數(shù)組中
6.私有的構(gòu)造函數(shù)除了成員變量外還有默認的兩個屬性
7.提供遍歷方法values()和根據(jù)name查詢枚舉實例

父類Enum源碼

public abstract class Enum<E extends Enum<E>>
        implements Comparable<E>, Serializable {

    private final String name;

    public final String name() {
        return name;
    }

    private final int ordinal;

    public final int ordinal() {
        return ordinal;
    }

    protected Enum(String name, int ordinal) {
        this.name = name;
        this.ordinal = ordinal;
    }

    public String toString() {
        return name;
    }

    public final boolean equals(Object other) {
        return this==other;
    }

    public final int hashCode() {
        return super.hashCode();
    }

    protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }

    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;
    }

    @SuppressWarnings("unchecked")
    public final Class<E> getDeclaringClass() {
        Class<?> clazz = getClass();
        Class<?> zuper = clazz.getSuperclass();
        return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper;
    }

    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);
    }

    protected final void finalize() { }

    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");
    }
}

關(guān)于父類Enum有兩個屬性,name和ordinal
name用來記錄名稱,也就是我們定義的名字NEW/FINISHED
ordinal用來記錄數(shù)組位置
Enum類equals方法比較地址,compareTo比較ordinal
不允許克隆,不允許反序列化

根據(jù)上面在衍生出其他花樣玩法
因為public static final OrderStatus,枚舉類可以直接==判斷
實現(xiàn)接口可以直接通過OrderStatus.NEW.method()
switch使用枚舉
枚舉類可以作為方法參數(shù),但是不要作為返回值
成員變量用final修飾,不要提供set方法
枚舉還能實現(xiàn)單例

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 簡介 枚舉是Java1.5引入的新特性,通過關(guān)鍵字enum來定義枚舉類。枚舉類是一種特殊類,它和普通類一樣可以使用...
    JimmieYang閱讀 43,776評論 4 75
  • 對象的創(chuàng)建與銷毀 Item 1: 使用static工廠方法,而不是構(gòu)造函數(shù)創(chuàng)建對象:僅僅是創(chuàng)建對象的方法,并非Fa...
    孫小磊閱讀 2,186評論 0 3
  • Chapter 6 Enums and Annotations 枚舉和注解 JAVA supports two s...
    LaMole閱讀 1,010評論 0 2
  • 一. Java基礎(chǔ)部分.................................................
    wy_sure閱讀 4,037評論 0 11
  • fdlso閱讀 84評論 0 0

友情鏈接更多精彩內(nèi)容