码迷,mamicode.com
首页 > 编程语言 > 详细

简单了解enum

时间:2017-12-08 12:14:30      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:nes   bre   val   sys   需要   命名   break   nal   编译器   

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类型,可以直接传递描述衣服尺码的字符串描述,变得更加简单、可读性更高。

简单了解enum

标签:nes   bre   val   sys   需要   命名   break   nal   编译器   

原文地址:http://www.cnblogs.com/aristole/p/8004421.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!