java 中的Enum

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

     /*
    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
    Enum的属性调用:

    下面的代码展示了调用enum对象的方法,这也是它通常的用法:

package  net.javagarage.enums;
    
/*
    File: EnumSwitch.java
    Purpose: show how to switch against the values in an enum.
    
*/

    
public   class  EnumSwitch  {
    
private enum Color { red, blue, green }
    
//list the values
    public static void main(String[] args) {
    
//refer to the qualified value
    doIt(Color.red);
    }

    
/*note that you switch against the UNQUALIFIED name. that is, "case Color.red:" is a
    compiler error 
*/

    
private static void doIt(Color c){
    
switch (c) {
    
case red:

    System.out.println(
"value is " + Color.red);
    
break;
    
case green:

    System.out.println(
"value is " + Color.green);
    
break;
    
case blue:

    System.out.println(
"value is : " + Color.blue);
    
break;
    
default :

    System.out.println(
"default");
    }

    }

    }


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值