zoukankan      html  css  js  c++  java
  • Java中的Enum的使用与分析


    使用name()方法和valueOf(String)方法可以在枚举类型对象和字符串之间方便得转换。
    如果valueOf(String)方法的参数不是该枚举类型合法的字符串,则会抛出IllegalArgumentException异常。
    Enum类提供了一个ordinal()方法,用来返回枚举对象的序数,比如本例中SPRING, SUMMER, AUTUMN, WINTER的序数就分别为0, 1, 2, 3。
    我们需要使用这个序数,而且还有可能再根据这个序数生成所需要的枚举对象
    eg1:

    package enums;
    
    public class EnumApiTest {
    
        public static void main(String[] args) {
            for (Shrubbery s : Shrubbery.values()) {
                System.out.println(s + " ordinal:" + s.ordinal());
                System.out.println(s.compareTo(Shrubbery.HANGING));
                System.out.println(s.equals(Shrubbery.CRAWLING));
                System.out.println(s == Shrubbery.GROUND);
                System.out.println(s.getDeclaringClass());
                System.out.println(s.name());
                System.out.println("   ");
            }
            System.out.println("=============");
    
            for (String s : "GROUND CRAWLING HANGING".split(" ")) {
                // Shrubbery shrub = Enum.valueOf(Shrubbery.class, s);
                Shrubbery shrub = Shrubbery.valueOf(s);
                System.out.println(shrub);
            }
    
        }
    
    }
    
    enum Shrubbery {
        GROUND,
        CRAWLING,
        HANGING;
    
        public Shrubbery valueOf(int ordinal) {
            if (ordinal >= values().length || ordinal < 0) {
                throw new IllegalArgumentException("IllegalArgument :" + ordinal);
            }
            return values()[ordinal];
        }
    
    }

    Output:

    GROUND ordinal:0
    -2
    false
    true
    class enums.Shrubbery
    GROUND
       
    CRAWLING ordinal:1
    -1
    true
    false
    class enums.Shrubbery
    CRAWLING
       
    HANGING ordinal:2
    0
    false
    false
    class enums.Shrubbery
    HANGING
       
    =============
    GROUND
    CRAWLING
    HANGING

    eg2:

    public enum EnumTest {
         FRANK("The given name of me"),
         LIU("The family name of me");//两个实例
         private String context;
         private String getContext(){
             return this.context;
         }
         private EnumTest(String context){
             this.context = context;
         }
         public static void main(String[] args){
             for(EnumTest name :EnumTest.values()){
                 System.out.println(name+" : "+name.getContext());
             }
             System.out.println(EnumTest.FRANK.getDeclaringClass());
         }
    } 


    Java中枚举实现的分析:
    eg3: 

    public enum Color{  
        RED,BLUE,BLACK,YELLOW,GREEN  
    } 

    显然,enum很像特殊的class,实际上enum声明定义的类型就是一个类。 而这些类都是类库中Enum类的子类(java.lang.Enum<E>)。它们继承了这个Enum中的许多有用的方法。我们对代码编译之后发现,编译器将enum类型单独编译成了一个字节码文件:Color.class。

    Color字节码代码

    final enum test.Color {  
        
     // 所有的枚举值都是类静态常量  
     public static final enum test.Color RED;  
     public static final enum test.Color BLUE;  
     public static final enum test.Color BLACK;  
     public static final enum test.Color YELLOW;  
     public static final enum test.Color GREEN;  
       
    private static final synthetic test.Color[] ENUM$VALUES;  
        
      // 初始化过程,对枚举类的所有枚举值对象进行第一次初始化  
     static {  
         0  new test.Color [1]   
         3  dup  
         4  ldc <String "RED"> [16] //把枚举值字符串"RED"压入操作数栈  
         6  iconst_0  // 把整型值0压入操作数栈  
         7  invokespecial test.Color(java.lang.String, int) [17] //调用Color类的私有构造器创建Color对象RED  
        10  putstatic test.Color.RED : test.Color [21]  //将枚举对象赋给Color的静态常量RED。  
          .........  枚举对象BLUE等与上同  
       102  return  
    };  
        
      // 私有构造器,外部不可能动态创建一个枚举类对象(也就是不可能动态创建一个枚举值)。  
     private Color(java.lang.String arg0, int arg1){  
         // 调用父类Enum的受保护构造器创建一个枚举对象  
         3  invokespecial java.lang.Enum(java.lang.String, int) [38]  
    };  
       
     public static hr.test.Color[] values();  
        
       // 实现Enum类的抽象方法    
      public static hr.test.Color valueOf(java.lang.String arg0);  
    }  

    下面我们就详细介绍enum定义的枚举类的特征及其用法。(后面均用Color举例)
    1、Color枚举类就是class,而且是一个不可以被继承的final类。其枚举值(RED,BLUE...)都是Color类型的类静态常量, 我们可以通过下面的方式来得到Color枚举类的一个实例:
     Color c=Color.RED; 
    注意:这些枚举值都是public static final的,也就是我们经常所定义的常量方式,因此枚举类中的枚举值最好全部大写。 

    2、即然枚举类是class,当然在枚举类型中有构造器,方法和数据域。但是,枚举类的构造器有很大的不同: 
          (1) 构造器只是在构造枚举值的时候被调用。

    enum Color {
        RED(255, 0, 0),
        BLUE(0, 0, 255),
        BLACK(0, 0, 0),
        YELLOW(255, 255, 0),
        GREEN(0, 255, 0);
        // 构造枚举值,比如RED(255,0,0)
        private Color(int r, int g, int b) {
            this.redValue = r;
            this.greenValue = g;
            this.blueValue = b;
        }
    
        public String toString() {
            return super.toString() + "(" + redValue + "," + greenValue + "," + blueValue + ")";
        }
    
        // 自定义数据域,private为了封装。
        private int redValue;
        private int greenValue;
        private int blueValue;
    }

         (2) 构造器只能私有private,绝对不允许有public构造器。 这样可以保证外部代码无法新构造枚举类的实例。这也是完全符合情理的,因为我们知道枚举值是public static final的常量而已。 但枚举类的方法和数据域可以允许外部访问。

    public static void main(String args[])  
    {  
            // Color colors=new Color(100,200,300);  //wrong  
               Color color=Color.RED;  
               System.out.println(color);  // 调用了toString()方法  
    }     

    3、所有枚举类都继承了Enum的方法,下面我们详细介绍这些方法。 
           (1)  ordinal()方法: 返回枚举值在枚举类种的顺序。这个顺序根据枚举值声明的顺序而定。
            Color.RED.ordinal();  //返回结果:0
            Color.BLUE.ordinal();  //返回结果:1
           (2)  compareTo()方法: Enum实现了java.lang.Comparable接口,因此可以比较象与指定对象的顺序。Enum中的compareTo返回的是两个枚举值的顺序之差。当然,前提是两个枚举值必须属于同一个枚举类,否则会抛出ClassCastException()异常。(具体可见源代码)
            Color.RED.compareTo(Color.BLUE);  //返回结果 -1
           (3)  values()方法: 静态方法,返回一个包含全部枚举值的数组。
                     Color[] colors=Color.values();
                     for(Color c:colors){
                            System.out.print(c+","); 
                     }//返回结果:RED,BLUE,BLACK YELLOW,GREEN,
           (4)  toString()方法: 返回枚举常量的名称。
                     Color c=Color.RED;
                     System.out.println(c);//返回结果: RED
           (5)  valueOf()方法: 这个方法和toString方法是相对应的,返回带指定名称的指定枚举类型的枚举常量。
                     Color.valueOf("BLUE");   //返回结果: Color.BLUE
           (6)  equals()方法: 比较两个枚举类对象的引用。

    //JDK源代码:      
    public final boolean equals(Object other) {  
            return this==other;  
    }          

    4、枚举类可以在switch语句中使用。

    Color color=Color.RED;  
    switch(color){  
            case RED: System.out.println("it's red");break;  
            case BLUE: System.out.println("it's blue");break;  
            case BLACK: System.out.println("it's blue");break;  
    }  
  • 相关阅读:
    Window—mysql下载及安装
    postgresql 在windows下启动调试功能
    FASTREPORT自动换行及行高自适应
    如何卸载已经安装在delphi7中控件包?
    cxgrid使用三问1cxgrid 如何动态创建列2cxGrid 通过字段名取得列3cxGrid动态创建的列里动态创建事件的方法
    VirtualBox中Linux设置共享文件夹
    Android & iOS 启动画面制作工具(转自龟山Aone)
    PostgreSQL 基本数据类型及常用SQL 函数操作
    win10 安装Postgresql 服务不能启动报错
    TdxDbOrgChart 图标显示问题
  • 原文地址:https://www.cnblogs.com/softidea/p/3760235.html
Copyright © 2011-2022 走看看