二十五、JDK1.5新特性---枚舉

        與上篇文章介紹的相同,本文也是介紹jdk 1.5出現的新特性,本文將介紹枚舉的相關用法。

在jdk 1.5 之前。Java可以有兩種方式定義新類型:類和接口。對於大部分面向對象來說。這兩種方法看起來似乎足夠了。但是在一些特殊情況下,這些方法就不合適。例如:想定義一個Color類,它只能由Red、Green、Blue三種值,其他的任何形式都是非法的。那麼jdk 1.5之前雖然可以構造出這樣的發image,但是要做很多的工作,也就可能帶來各種不安全的問題。而在 jdk 1.5之後引入的枚舉類型(Enum)就能避免這些問題。

        所謂的枚舉就是規定好了指定的取值範圍,所以都得內容只能從指定的範圍中取得。使用簡單類完成顏色的固定取值問題。也就是說一個類只能產生固定的幾個對象。例如:

        package enum_;

        class Color{

           public static final Color RED=new Color("紅色");// 定義第一個對象

           public static final Color GREEN=new Color("綠色");// 定義第一個對象

            public static final Color BLUE=new Color("藍色");// 定義第一個對象

            private String name;

            Color(String name){

                this.name=name;

    }

    public static Color getInstance(int i){

        switch(i){

        case 1:return RED;

        case 2:return GREEN;

        case 3:return BLUE;

        default:return null;

        }

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

}

public class ColorDemo1 {

    public static void main(String[] args) {

        Color c1=Color.RED;//取得紅色

        System.out.println(c1.getName());

        Color c2=Color.getInstance(3);

        System.out.println(c2.getName());

    }

   

}

        此時程序限定了所能取的對象的範圍,所以達到了枚舉的功能,以上是一種枚舉的方式,在早期的java開發中沒有沒有枚舉這個概念,所以有時候也可以使用接口表示。

interface Color{

    public static final int RED = 1 ;    // 定義紅色

    public static final int GREEN = 2 ;    // 定義綠色

    public static final int BLUE = 3 ;    // 定義藍色

}

        因爲以上的所有取值都是直接使用數字表示的,所以操作的時候會存在一些問題。比如:

public class ColorDemo02{

    public static void main(String args[]){

        System.out.println(Color.RED + Color.GREEN) ;    // 顏色相加

    }

}

        這個操作並不是很明確,所以在jdk 1.5之前如果要實現枚舉操作就會比較麻煩。

Enum

    從上文的描述可以清晰的瞭解到,使用enum關鍵字可以定義一個枚舉,實際上這個關鍵字是java.lang.Enum類型,即使用enum聲明的枚舉類型相當於定義了一個類,只是這個類默認繼承java.lang.Enum

枚舉類的主要操作方法

protected

Enum(String name, int ordinal)
          單獨的構造方法

int

compareTo(E o)
          比較此枚舉與指定對象的順序。

boolean

equals(Object other)
          當指定對象等於此枚舉常量時,返回 true。

protected  void

finalize()
          枚舉類不能有 finalize 方法。

 Class<E>

getDeclaringClass()
          返回與此枚舉常量的枚舉類型相對應的 Class 對象。

int

hashCode()
          返回枚舉常量的哈希碼。

 String

name()
          返回此枚舉常量的名稱,在其枚舉聲明中對其進行聲明。

int

ordinal()
          返回枚舉常量的序數(它在枚舉聲明中的位置,其中初始常量序數爲零)。

 String

toString()
          返回枚舉常量的名稱,它包含在聲明中。

static

<T extends Enum<T>>
T

valueOf(Class<T> enumType, String name)
          返回帶指定名稱的指定枚舉類型的枚舉常量。

 

構造方法介紹

        構造方法中接收兩個參數,一個表示枚舉的名字,另一個表示枚舉的序號(從0開始)

protected     Enum(String name, int ordinal)

 

構造枚舉的第一種方式

enum Color{

    RED,GREEN,BLUE;

}

        上面的方法是一種簡單的形式,在我們開發中遇到的情況往往比較複雜,比如使用一些文字表述定義枚舉對象的信息,這時就需要使用第二種方式了。

enum Color{

    RED("紅色"),GREEN("綠色"),BLUE("藍色");

    private String name;

    private Color(String name){

        this.name=name;

    }

}

如果不想通過構造實現設置內容,二十希望通過setter()方法實現,這時就必須按照以下的方式執行

enum Color {

    RED, GREEN, BLUE;

    private String name;

 

    public String getName() {

        return name;

    }

    public void setName(String name) {

        switch (this) {

        case RED:

            if ("紅色".equals(name))

                this.name = name;//允許設置名字

            else

                System.out.println("設置內容錯誤");

            break;

 

        case GREEN:

            if ("藍色".equals(name))

                this.name = name;//允許設置名字

            else

                System.out.println("設置內容錯誤");

            break;

        case BLUE:

            if ("綠色".equals(name))

                this.name = name;//允許設置名字

            else

                System.out.println("設置內容錯誤");

            break;

        }

 

    }

 

}

集合框架對Enum的支持

EnumMap

類 EnumMap<K extends Enum<K>,V>

java.lang.Object

java.util.AbstractMap<K,V>

java.util.EnumMap<K,V>

所有已實現的接口:

Serializable, Cloneable, Map<K,V>

 

案例示範

enum Color {

    RED, GREEN, BLUE;

    }

public class EnumMapDemo {

    public static void main(String[] args) {

        Map<Color ,String >desc=null;//定義Map對象,同時指定類型

        desc=new EnumMap<Color,String>(Color.class);//實例化EnumMap

        desc.put(Color.RED,"紅色");

        desc.put(Color.GREEN,"率色");

        desc.put(Color.BLUE,"藍色");

        System.out.println("====輸出所有內容====");

        for(Color c:Color.values()){

            System.out.println(c.name()+":"+desc.get(c));

        }

        System.out.println("====輸出所有鍵====");

        for(Color c:desc.keySet()){

            System.out.print(c.name()+"");

        }

        System.out.println("====輸出所有值====");

        for(String s:desc.values()){

            System.out.print(s+"");

        }

    }

}

 

EnumSet

    EnumSet是Set接口的子類,所以裏面的元素是無法重複的,在使用EnumSet的時候是不能直接使用關鍵字new爲其進行實例化的,所以在此類中提供了很多的靜態方法。

案例示範:

 

enum Color {

    RED, GREEN, BLUE;

}

 

public class EnumSetDemo {

    public static void main(String[] args) {

        demo1();

        demo2();

        demo3();

        demo4();

        demo5();

    }

 

    // 將枚舉中的所有元素放到EnumSet

    private static void demo1() {

        EnumSet<Color> es = null;// 聲明一個EnumSet集合

        System.out.println("===EnumSet.allOf(Color.class)===");

        es = EnumSet.allOf(Color.class);// 將枚舉中的所有元素放到EnumSet

        print(es);

    }

 

    // 只設置一個元素到集合中

    private static void demo2() {

        EnumSet<Color> es = null;// 聲明一個EnumSet集合

        System.out.println("===EnumSet.Of(Color.BLUE)===");

        es = EnumSet.of(Color.BLUE);// 爲集合添加指定的一個元素

        print(es);// 打印該集合

    }

 

    // 創建只能存放指定枚舉類型的集合

    private static void demo3() {

        EnumSet<Color> es = null;// 聲明一個EnumSet集合

        System.out.println("===EnumSet.noneOf(Color.class)===");

        es = EnumSet.noneOf(Color.class);// 指定es爲只能添加Color事例的集合

        es.add(Color.BLUE);// 添加元素

        // es.add("我的顏色");編譯不通過

        print(es);

 

    }

 

    // 創建不包含指定元素的集合

    private static void demo4() {

        EnumSet<Color> es = null;// 聲明一個EnumSet集合

        System.out.println("===EnumSet.complementOf(Color.BLUE)===");

        es = EnumSet.noneOf(Color.class);// 指定es爲只能添加Color事例的集合

        es.add(Color.BLUE);// 添加元素

        es.add(Color.RED);// 添加元素

        EnumSet<Color> esNew = null;

        esNew = EnumSet.complementOf(es);// 新的集合不包含上面指定元素

        print(esNew);

    }

 

    // 拷貝一個集合

    private static void demo5() {

        EnumSet<Color> es = null;// 聲明一個EnumSet集合

        System.out.println("===EnumSet.copyOf(Color.BLUE)===");

        es = EnumSet.noneOf(Color.class);// 指定es爲只能添加Color事例的集合

        es.add(Color.BLUE);// 添加元素

        es.add(Color.RED);// 添加元素

        EnumSet<Color> esNew = null;

        esNew = EnumSet.copyOf(es);// 將一個集合拷貝給另一個集合

        print(esNew);// 打印該集合

    }

 

    private static void print(EnumSet<Color> es) {// 專門用來輸出的操作

        for (Color c : es) {// 循環輸出EnumSet中的內容

            System.out.print(c + "");

        }

        System.out.println();

    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章