我使用枚举创建了几个常量:
enum ids {OPEN, CLOSE};
OPEN值为0,但我希望它为100。这可能吗?
我使用枚举创建了几个常量:
enum ids {OPEN, CLOSE};
OPEN值为0,但我希望它为100。这可能吗?
当前回答
用这种方式有什么好处:
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;
}
}
注意,这两种方法使用更少的内存和更多的进程单元。我并不是说这是最好的方法,但这只是另一种方法。
其他回答
@scottf
enum类似于Singleton。JVM创建实例。
如果你自己用类创建它,它可能是这样的
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
@Override
public String toString(){
return enumValue;
}
}
并且可以这样使用:
public class HelloWorld{
public static class MyEnum {
final public static MyEnum ONE;
final public static MyEnum TWO;
static {
ONE = new MyEnum("1");
TWO = new MyEnum("2");
}
final String enumValue;
private MyEnum(String value){
enumValue = value;
}
@Override
public String toString(){
return enumValue;
}
}
public static void main(String []args){
System.out.println(MyEnum.ONE);
System.out.println(MyEnum.TWO);
System.out.println(MyEnum.ONE == MyEnum.ONE);
System.out.println("Hello World");
}
}
如果你想模拟C/ c++的enum(以num为基数,next为增量):
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());
}
}
}
开放0 100 Close 1 101
是的。你可以将数值传递给枚举的构造函数,如下所示:
enum Ids {
OPEN(100),
CLOSE(200);
private int value;
private Ids(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
有关更多信息,请参阅Sun Java语言指南。
用这种方式有什么好处:
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;
}
}
注意,这两种方法使用更少的内存和更多的进程单元。我并不是说这是最好的方法,但这只是另一种方法。
函数的作用是:返回标识符在枚举中的相对位置。您可以使用它来获得带有偏移量的自动索引,就像使用c风格的enum一样。
例子:
public class TestEnum {
enum ids {
OPEN,
CLOSE,
OTHER;
public final int value = 100 + ordinal();
};
public static void main(String arg[]) {
System.out.println("OPEN: " + ids.OPEN.value);
System.out.println("CLOSE: " + ids.CLOSE.value);
System.out.println("OTHER: " + ids.OTHER.value);
}
};
给出输出:
OPEN: 100
CLOSE: 101
OTHER: 102
编辑:刚刚意识到这与ggrandes的答案非常相似,但我将把它留在这里,因为它非常干净,并且与C风格的enum非常接近。