Java 1.5新特性Enum的用法

來源:互聯網
上載者:User

Enum是enumeration(列舉)的簡寫形式,包含在java.lang包中.熟悉C,C++,C#,或Pascal人應該對列舉有所瞭解,先看個例子:

public enum Season { winter, spring, summer, fall }

一個enum是定義一組值的對象,它可以包括零個或多個值成員.它是屬於enum類型的,一個enum對象中不可有兩個或多個相同的屬性或值.在次之前的java程式員一般是用介面的方法實現列舉的,如:

public interface Season {
  static winter = 0;
  static spring = 1; //etc……
  }

引入了enum的java的列舉的編寫方便了許多,只須定義一個enum型的對象.enum對象的值都回自動獲得一個數字值,從0開始,依次遞增.看一個比較簡單的enum實現的例子:

EnumDemo.java
  package net.javagarage.enums;
  /*
  We can loop over the values we put into the enum
  using the values() method.
  Note that the enum Seasons is compiled into a
  separate unit, called EnumDemo$Seasons.class
  */
  public class EnumDemo {
  /*declare the enum and add values to it. note that, like in C#, we don't use a ; to
  end this statement and we use commas to separate the values */
  private enum Seasons { winter, spring,
  summer, fall }
  //list the values
  public static void main(String[] args) {
  for (Seasons s : Seasons.values()){
  System.out.println(s);
  }
  }
  }

運行上述代碼你回得到以下結果:

winter

spring

summer

fall

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.