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

  • 相关阅读:
    利用Python和webhook实现自动提交代码
    Python threading 单线程 timer重复调用函数
    Python requests 使用心得
    openresty实现接口签名安全认证
    使用jedis面临的非线程安全问题
    记一次线上升级openresty中kafka版本产生的多版本兼容问题
    mysql中走与不走索引的情况汇集(待全量实验)
    Elasticsearch深分页以及排序查询问题
    IO多路复用:Redis中经典的Reactor设计模式
    Netty在Dubbo中的使用过程源码分析
  • 原文地址:https://www.cnblogs.com/aristole/p/8004421.html
Copyright © 2011-2022 走看看