Java 枚舉類

來源:互聯網
上載者:User

標籤:arrays   直接   color   ora   target   util   stat   targe   system   

參考部落格:  http://www.cnblogs.com/zhaoyanjun/p/5659811.html

直接上代碼:

 1 import java.util.HashMap; 2 import java.util.Map; 3 //import java.lang.Enum;  //這TM是預設匯入的包 4  5 public enum Color { 6     WHITE(1,"WHITE"), 7     RED(2,"RED"), 8     ORANGE(3,"ORANGE"), 9     YELLOW(4,"YELLOW"),10     GREEN(5,"GREEN"),11     BLUE(6,"BLUE"),12     PURPLE(7,"PURPLE"),13     BLACK(8,"BLACK")14     ;15     16     private Integer id;17     private String name;18     19     private Color(Integer id, String name) {20         this.id = id;21         this.name = name;22     }23     24     public Integer getId() {25         return id;26     }27     28     public String getName() {29         return name;30     }31     //到上面截至是一般枚舉類的基本寫法32     33     private static Map<Integer, Color> map = new HashMap<Integer, Color>();34     35     static {36         for(Color enums : Color.values()) {//後面會講到這個方法輸出的是什麼37             map.put(enums.getId(), enums);38         }39     }40     41     public static Color valueOf(int id) {//看清楚傳回值42         return valueOf(id, null);43     }44     45     public static Color valueOf(int id, Color color) {46         Color result = map.get(id);47         return result == null ? color : result;48     }49     50     //比如實際應用中可能有一些特殊的癖好列出所有顏色的名字  51     public static String[] listAllColor() {52         Color[] colors = Color.values();53         String[] result = new String[colors.length];54         for(int i = 0; i < colors.length; i++) {55             result[i] = colors[i].getName();56         }57         return result;58     }59     60     //再比如我想寫一個nameOf61     public static String nameOf(int id) {62         Color temp = map.get(id);63         return temp == null ? null : temp.getName();64     }65 }

測試一下:

1     public static void main(String[] args) {2         //Hello World3         System.out.println(4                 Arrays.toString(Color.values()));5         System.out.println(Color.valueOf(3).getName());6         System.out.println(Color.nameOf(3));7         System.out.println(8                 Arrays.toString(Color.listAllColor()));9     }

結果如下:

好了講一下values這個方法返回的是什麼,返回的是那些枚舉對象的名字不是name。

或者說返回的是枚舉類下的所有枚舉。

改成這個樣子,運行結果如下:

這下明白返回的是啥了吧。

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.