开发者

Java enum set custom ordinals [duplicate]

This question already has answers here: Can I specify ordinal for enum in Java? (7 answers) 开发者_如何学Python Closed 7 years ago.

The other day I tried to do this, but it doesn't work:

enum MyEnum {ONE = 1, TWO = 2}

much to my surprise, it doesn't compile!!! How to se custom ordinals???


You can't. Ordinals are fixed by starting at 0 and working up. From the docs for ordinal():

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

You can't assign your own values. On the other hand, you can have your own values in the enum:

public enum Foo {
    ONE(1), TWO(2);

    private final int number;

    private Foo(int number) {
        this.number = number;
    }

    public int getNumber() {
        return number;
    }
}


This is how you could do it manually:

enum MyEnum {
    ONE(1), 
    TWO(2);

    private int val;

    private MyEnum(int val) {
        this.val = val;
    }
}


The order in which you define the enums will determine the ordinals.

enum MyEnum {
    Enum1, Enum2;
}

Here, Enum1 will have ordinal 1 and Enum2 will have ordinal 2.

But you can have custom properties for each enum:

enum MyEnum {
    Enum1(1), Enum2(2);

    private int ord ;

    MyEnum(int ord) {
        this.ord = ord;
    }

    public int getOrd() {
        return this.ord;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜