2009-07-01 76 views

回答

252

Java枚舉不像C或C++枚舉,它們實際上只是整數的標籤。

Java枚舉類實現更像類 - 而且它們甚至可以有多個屬性。

public enum Ids { 
    OPEN(100), CLOSE(200); 

    private final int id; 
    Ids(int id) { this.id = id; } 
    public int getValue() { return id; } 
} 

最大的區別是,他們是類型安全這意味着你不必擔心的大小可變分配COLOR枚舉。

查看http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html瞭解更多。

+0

根據您的聲明,使用java創建順序整數的枚舉(類似於C++枚舉)的最佳實踐,對於索引到數組或類似內容,應寫入: enum (0), AGE(1), HEIGHT(2), WEIGHT(3); } 謝謝, -bn – 2009-08-13 19:35:56

73

是的。您可以通過數值來構造的枚舉,像這樣:

enum Ids { 
    OPEN(100), 
    CLOSE(200); 

    private int value;  

    private Ids(int value) { 
    this.value = value; 
    } 

    public int getValue() { 
    return value; 
    } 
} 

更多信息,請參見Sun Java Language Guide

+0

酷。可以混合嗎?即只將數字分配給選定的枚舉值。 – 2016-10-19 08:39:20

+0

私有修飾符對於枚舉構造函數是多餘的 – 2017-01-16 14:53:09

10

如果你使用非常大的枚舉類型,那麼以下是有用的;

10

什麼關於使用這種方式:

public enum HL_COLORS{ 
      YELLOW, 
      ORANGE; 

      public int getColorValue() { 
       switch (this) { 
      case YELLOW: 
       return 0xffffff00; 
      case ORANGE: 
       return 0xffffa500;  
      default://YELLOW 
       return 0xffffff00; 
      } 
      } 
} 

只有一個方法..

可以使用靜態方法並傳遞枚舉作爲參數 像:

public enum HL_COLORS{ 
      YELLOW, 
      ORANGE; 

      public static int getColorValue(HL_COLORS hl) { 
       switch (hl) { 
      case YELLOW: 
       return 0xffffff00; 
      case ORANGE: 
       return 0xffffa500;  
      default://YELLOW 
       return 0xffffff00; 
      } 
      } 

請注意,這兩種方式使用更少的內存和更多的流程單位..我不'不要說這是最好的方法,但它只是另一種方法。

2

如果你想模仿C/C++(NUM基地和增量的nextS)的枚舉:

enum ids { 
    OPEN, CLOSE; 
    // 
    private static final int BASE_ORDINAL = 100; 
    public int getCode() { 
     return ordinal() + BASE_ORDINAL; 
    } 
}; 

public class TestEnum { 
    public static void main (String... args){ 
     for (ids i : new ids[] { ids.OPEN, ids.CLOSE }) { 
      System.out.println(i.toString() + " " + 
       i.ordinal() + " " + 
       i.getCode()); 
     } 
    } 
} 
OPEN 0 100 
CLOSE 1 101 
相關問題