Java 枚舉7常見種用法

來源:互聯網
上載者:User

        DK1.5引入了新的類型——枚舉。在Java中它雖然算個“小”功能,卻給我的開發帶來了“大”方便。

用法一:常量

        在JDK1.5之前,我們定義常量都是:public static fianl ....。現在好了,有了枚舉,可以把相關的常量分組到一個枚舉類型裡,而且枚舉提供了比常量更多的方法。

public enum Color {  RED, GREEN, BLANK, YELLOW}

用法二:switch

        JDK1.6之前的switch語句只支援int,char,enum類型,使用枚舉,能讓我們的代碼可讀性更強。

enum Signal {GREEN, YELLOW, RED}public class TrafficLight {Signal color = Signal.RED;public void change() {switch (color) {case RED:color = Signal.GREEN;break;case YELLOW:color = Signal.RED;break;case GREEN:color = Signal.YELLOW;break;}}}

用法三:向枚舉中添加新方法

        如果打算自訂自己的方法,那麼必須在enum執行個體序列的最後添加一個分號。而且Java要求必須先定義enum執行個體。

public enum Color {RED("紅色", 1), GREEN("綠色", 2), BLANK("白色", 3), YELLO("黃色", 4);// 成員變數private String name;private int index;// 構造方法private Color(String name, int index) {this.name = name;this.index = index;}// 普通方法public static String getName(int index) {for (Color c : Color.values()) {if (c.getIndex() == index) {return c.name;}}return null;}// get set 方法public String getName() {return name;}public void setName(String name) {this.name = name;}public int getIndex() {return index;}public void setIndex(int index) {this.index = index;}}

用法四:覆蓋枚舉的方法

        下面給出一個toString()方法覆蓋的例子。

public enum Color {RED("紅色", 1), GREEN("綠色", 2), BLANK("白色", 3), YELLO("黃色", 4);// 成員變數private String name;private int index;// 構造方法private Color(String name, int index) {this.name = name;this.index = index;}//覆蓋方法@Overridepublic String toString() {return this.index+"_"+this.name;}}

用法五:實現介面

        所有的枚舉都繼承自java.lang.Enum類。由於Java不支援多繼承,所以枚舉對象不能再繼承其他類。

public interface Behaviour {void print();String getInfo();}public enum Color implements Behaviour{RED("紅色", 1), GREEN("綠色", 2), BLANK("白色", 3), YELLO("黃色", 4);// 成員變數private String name;private int index;// 構造方法private Color(String name, int index) {this.name = name;this.index = index;}//介面方法@Overridepublic String getInfo() {return this.name;}//介面方法@Overridepublic void print() {System.out.println(this.index+":"+this.name);}}

用法六:使用介面組織枚舉

public interface Food {enum Coffee implements Food{BLACK_COFFEE,DECAF_COFFEE,LATTE,CAPPUCCINO}enum Dessert implements Food{FRUIT, CAKE, GELATO}}

用法七:關於枚舉集合的使用

        java.util.EnumSet和java.util.EnumMap是兩個枚舉集合。EnumSet保證集合中的元素不重複;EnumMap中的key是enum類型,而value則可以是任意類型。關於這個兩個集合的使用就不在這裡贅述,可以參考JDK文檔。

        關於枚舉的實現細節和原理請參考:

        參考資料:《Thinking In Java》 第四版

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.