zoukankan      html  css  js  c++  java
  • 简单了解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类型,可以直接传递描述衣服尺码的字符串描述,变得更加简单、可读性更高。

  • 相关阅读:
    POJ1321 棋盘问题
    HDU1234 开门人和关门人(解法二)
    HDU1234 开门人和关门人(解法二)
    HDU1996 汉诺塔VI
    HDU1996 汉诺塔VI
    HDU1013 POJ1519 Digital Roots(解法二)
    HDU1013 POJ1519 Digital Roots(解法二)
    HDU4548 美素数
    HDU4548 美素数
    POJ3751 时间日期格式转换【日期计算】
  • 原文地址:https://www.cnblogs.com/aristole/p/8004421.html
Copyright © 2011-2022 走看看