Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum set custom ordinals [duplicate]

Tags:

java

enums

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

like image 588
gotch4 Avatar asked Sep 26 '11 18:09

gotch4


1 Answers

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;     } } 
like image 101
Jon Skeet Avatar answered Sep 19 '22 03:09

Jon Skeet