枚舉(enum)類型是Java 5新增的特性,它是一種新的類型,允許用常量來表示特定的數據片斷,而且全部都以類型安全的形式來表示。
1、常量的使用
在JDK1.5之前,我們定義常量都是:public static fianl....。現在好了,有了枚舉,可以把相關的常量分組到一個枚舉類型里,而且枚舉提供了比常量更多的方法。
package com; public enum Color {      RED, GREEN, BLANK, YELLOW  }使用
package com; public class B {   public static void main(String[] args) {      System.out.println( isRed( Color.BLANK ) ) ; //結果: false    System.out.println( isRed( Color.RED ) ) ;  //結果: true   }    static boolean isRed( Color color ){    if ( Color.RED.equals( color )) {      return true ;    }    return false ;  } }或者 switch 的使用
package com; public class B {   public static void main(String[] args) {     showColor( Color.RED );   }   static void showColor(Color color){    switch ( color ) {    case BLANK:      System.out.println( color );      break;    case RED :      System.out.println( color );      break;    default:      System.out.println( color );      break;    }       }}2、自定義函數
package com; 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 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;  }    }使用
package com; public class B {   public static void main(String[] args) {     //輸出某一枚舉的值    System.out.println( Color.RED.getName() );    System.out.println( Color.RED.getIndex() );     //遍歷所有的枚舉    for( Color color : Color.values()){      System.out.println( color + " name: " + color.getName() + " index: " + color.getIndex() );    }  } }結果
紅色
1
RED name: 紅色 index: 1
GREEN name: 綠色 index: 2
BLANK name: 白色 index: 3
YELLO name: 黃色 index: 4
總結:
1、枚舉的本質是類,在沒有枚舉之前,仍然可以按照java最基本的編程手段來解決需要用到枚舉的地方。枚舉屏蔽了枚舉值的類型信息,不像在用public static final定義變量必須指定類型。枚舉是用來構建常量數據結構的模板,這個模板可擴展。枚舉的使用增強了程序的健壯性,比如在引用一個不存在的枚舉值的時候,編譯器會報錯。枚舉的更多用法還需要在開發中去研究創造,Java5、Java6增加了不少新的特性,技術在升級,對程序員來說就要學習,如果你熱愛java的話。否則別人用到新特性的代碼你看不懂,那才叫郁悶。
2、枚舉在Java家族中只占了很小的一塊比重,所以我在項目中用枚舉的地方不是很多,畢竟,一個項目是很多人開發維護的,用一個陌生的東西,會給其他的同事造成閱讀困難。所以常量大都是用public static final 來定義的。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答