简单了解enum

enum的性质:

  1.枚举类型的实例都是常量

  2.要使用enum,需要创建一个该类型的引用,并将其赋值给某个实例

  3.常用的方法:

     *     toString():某个enum实例的名字
     *     ordinal():某个enum实例的声明顺序
     *     values():按照enum常量的声明顺序,产生由这些常量构成的数组

  4.可以把enum当做一般类来处理,它有自己的方法

 

例子:enum与switch-case结合使用

public enum Spiciness {
    // 枚举类型的实例是常量,按照惯例使用大写命名
    NOT, MILD, MEDIUM, HOT, FLAMING
}

/*
 * enum关键字为enum生成对应的类时,产生某些编译器行为,因此在很大程度上可以把enum
 * 当做其他任何类来处理
 */
public class Burrito {
    Spiciness degree;
    
    public Burrito(Spiciness degree){
        this.degree = degree;
    }
    
    public void describe(){
        System.out.print("This burrito is ");
        switch(degree){
            case NOT:    System.out.println("not spicy at all");
                        break;
            case MILD:    System.out.println("a little hot");
                        break;
            case HOT:
            case FLAMING:
            default:    System.out.println("maybe too hot");
                        break;
        }
    }
    
    public static void main(String[] args) {
        Burrito plain = new Burrito(Spiciness.NOT),
                greenChile = new Burrito(Spiciness.MEDIUM),
                jalapeno = new Burrito(Spiciness.HOT);
        plain.describe();
        greenChile.describe();
        jalapeno.describe();
    }
}
/*output:
This burrito is not spicy at all
This burrito is maybe too hot
This burrito is maybe too hot
*/

分析:

  在jdk1.6之前,switch-case只能接收int型参数(或者可以向上转型为int型的参数,例如:byte, char, short)和enum;在jdk之后的版本可以接收String类型参数。也就是说,若在以前,为了在switch-case中根据衣服的尺码做不一样的操作时,较简单的实现是使用enum;现在增加了String类型,可以直接传递描述衣服尺码的字符串描述,变得更加简单、可读性更高。

posted @ 2017-12-08 11:01  Aristole  阅读(213)  评论(0编辑  收藏  举报