Java筆記:枚舉

來源:互聯網
上載者:User

標籤:繼承   rgs   比較   system   差值   通過   ret   post   for   

一、基礎知識

枚舉常量為枚舉類型中的公有靜態成員,且其類型是聲明他們的枚舉類型。這些常量被稱為是自類型化的。由於是靜態常量,所以可直接使用關係運算子來比較兩個枚舉常量是否相等。此外可通過枚舉類型定義的values方法和valueOf方法擷取枚舉常量數值。

class Solution {    enum Color {        RED, BLUE, GREEN    }    public static void main(String[] args) {        Color[] colors = Color.values();        for (Color c : colors)            System.out.println(c);    }}

枚舉常量是其枚舉類型的對象,在定義枚舉類型時可定義建構函式和方法。所有的枚舉都會自動繼承java.lang.Enum,部分方法如下:

  • ordinal方法返回枚舉常量的序數值。
  • compareTo方法返回與同類型其他枚舉常量比較的差值。
  • equals方法返回與同類型其他枚舉常量是否相等。
class Solution {    enum Color {        RED("#FF0000"), BLUE("#0000FF"), GREEN("#00FF00");        private String code;        Color(String code) {            this.code = code;        }        String getCode() {            return code;        }    }    public static void main(String[] args) {        System.out.println(Color.valueOf("RED"));//輸出RED        System.out.println(Color.valueOf("BLUE"));//輸出BLUE        System.out.println(Color.valueOf("GREEN"));//輸出GREEN        Color[] colors = Color.values();        for (Color c : colors)            System.out.println(c.ordinal());        for (Color i : colors)            for (Color j : colors) {                System.out.println(i.compareTo(j));//返回i.ordinal - j.ordinal                System.out.println(i.equals(j));            }    }}

 

Java筆記:枚舉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.