Java列舉使用

weixin_34162629發表於2017-10-24

 在JDK1.5 之前,我們定義常量都是: public static fianl.... 。

現在好了,有了列舉,可以把相關的常量分組到一個列舉型別裡,而且列舉提供了比常量更多的方法。

 

1、不用列舉

package First;

public class Test {

    public static final int RED = 1; 
    public static final int Green = 3;  
    public static final int YELLOW = 2;

    
    public static void main(String[] args) {
        int value = Test.Green;
        System.out.println(value);
    }
}


2、用列舉:改變上面

 

package First;

public class LightTest {

    public enum Light{
        
        RED(1),Green(3),YELLOW(2);
        
        private int nCode;
        
        /*
         * 1. private型別的建構函式
         * 2. 給變數賦值
         */
        private Light(int nCode){
            this.nCode = nCode;
        }
        /*
         * 獲取各個變數的值
         */
        public int getValue(){
            return nCode;
        }
        
    }
    
    public static void main(String[] args) {
        
        
        Light light = Light.Green;
        int value = light.getValue();
        System.out.println(value);
        
        System.out.println("----------------");
        
        //遍歷
        Light[] lights = Light.values();
        for(Light a : lights){
            System.out.println(a);
            System.out.println(a.nCode);
        }
        
    }
    
    
}

 

3、用列舉:多個引數

 

package First;

public class LightTest {

    public enum Light{
        
        RED(1,"紅"),Green(3,"綠"),YELLOW(2,"黃");
        
        private int nCode;
        private String str;
        
        /*
         * 1. private型別的建構函式
         * 2. 給變數賦值
         */
        private Light(int nCode, String str){
            this.nCode = nCode;
            this.str = str;
        }
        /*
         * 獲取各個變數的值
         */
        public int getValue(){
            return nCode;
        }
        
        public String getStr(){
            return str;
        }
        
    }
    
    public static void main(String[] args) {
        
        Light light = Light.Green;
        int value = light.getValue();
        String str = light.getStr();
        
        System.out.println(value);
        System.out.println(str);
        
    }
    
    
}

 

相關文章