可以在java中设置枚举开始值

我使用枚举做一些常量:

enum ids {OPEN, CLOSE}; 

OPEN值是零,但我想它为100.是否有可能?

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; } } 

最大的区别是它们是types安全的 ,这意味着您不必担心将COLOR枚举赋给SIZEvariables。

有关更多信息,请参阅http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

是。 您可以将数值传递给枚举的构造函数,如下所示:

 enum Ids { OPEN(100), CLOSE(200); private int value; private Ids(int value) { this.value = value; } public int getValue() { return value; } } 

有关更多信息,请参阅“ Sun Java语言指南” 。

如果您使用非常大的枚举types,那么以下是有用的;

 public enum deneme { UPDATE, UPDATE_FAILED; private static Map<Integer, deneme> ss = new TreeMap<Integer,deneme>(); private static final int START_VALUE = 100; private int value; static { for(int i=0;i<values().length;i++) { values()[i].value = START_VALUE + i; ss.put(values()[i].value, values()[i]); } } public static deneme fromInt(int i) { return ss.get(i); } public int value() { return value; } } 

有什么关于使用这种方式:

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

只有一种方法..

您可以使用静态方法并传递Enum作为参数,如:

 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; } } 

请注意,这两种方式使用较less的内存和更多的stream程单位..我不认为这是最好的办法,但它只是另一种方法。

如果你想模拟C / C ++的枚举(base num和nexts incrementals):

 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