Java中的枚舉類型

來源:互聯網
上載者:User
public class TestEnum {    /*最普通的枚舉*/    public enum ColorSelect {        red, green, yellow, blue;        }    /* 枚舉也可以象一般的類一樣添加方法和屬性,你可以為它添加靜態和非靜態屬性或方法,這一切都象你在一般的類中做的那樣. */    public enum Season {        // 枚舉列表必須寫在最前面,否則編譯出錯        winter, spring, summer, fall;        private final static String location = "Phoenix";                public static Season getBest() {            if (location.equals("Phoenix"))                return winter;            else                return summer;        }    }    /*還可以有構造方法*/    public enum Temp {        /*通過括弧賦值,而且必須有帶參構造器和一屬性跟方法,否則編譯出錯         * 賦值必須是都賦值或都不賦值,不能一部分賦值一部分不賦值         * 如果不賦值則不能寫構造器,賦值編譯也出錯*/        absoluteZero(-459), freezing(32),boiling(212), paperBurns(451);                private final int value;        public int getValue() {            return value;        }        //構造器預設也只能是private, 從而保證建構函式只能在內部使用        Temp(int value) {            this.value = value;        }    }    public static void main(String[] args) {        /*         * 枚舉類型是一種類型,用於定義變數,以限制變數的賦值 賦值時通過"枚舉名.值"來取得相關枚舉中的值         */        ColorSelect m = ColorSelect.blue;        switch (m) {        /*注意:枚舉重寫了ToString(),說以枚舉變數的值是不帶首碼的          *所以為blue而非ColorSelect.blue          */   case red:            System.out.println("color is red");            break;        case green:            System.out.println("color is green");            break;        case yellow:            System.out.println("color is yellow");            break;        case blue:            System.out.println("color is blue");            break;        }        System.out.println("遍曆ColorSelect中的值");        /*通過values()獲得枚舉值的數組*/        for (ColorSelect c : ColorSelect.values()) {            System.out.println(c);        }     System.out.println("枚舉ColorSelect中的值有:"+ColorSelect.values().length+"個");   /*ordinal()返回枚舉值在枚舉中的索引位置,從0開始*/  System.out.println(ColorSelect.red.ordinal());//0  System.out.println(ColorSelect.green.ordinal());//1  System.out.println(ColorSelect.yellow.ordinal());//2  System.out.println(ColorSelect.blue.ordinal());//3  /*枚舉預設實現了java.lang.Comparable介面*/   System.out.println(ColorSelect.red.compareTo(ColorSelect.green));  System.out.println(Season.getBest());                for(Temp t:Temp.values()){            /*通過getValue()取得相關枚舉的值*/            System.out.println(t+"的值是"+t.getValue());        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.