29

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???

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
gotch4
  • 13,093
  • 29
  • 107
  • 170

3 Answers3

50

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;
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • how does this interfere with indexing into the enums `.values()` ? Wouldn't it be better to write a enum-like class or maybe use a map to avoid unexpected results? – 463035818_is_not_an_ai Aug 13 '18 at 16:05
7

This is how you could do it manually:

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

    private int val;

    private MyEnum(int val) {
        this.val = val;
    }
}
Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
1

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;
    }
}
Hari Menon
  • 33,649
  • 14
  • 85
  • 108