2009-07-01 72 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 
相关问题