Can I specify ordinal for enum in Java?

You can control the ordinal by changing the order of the enum, but you cannot set it explicitly like in C++. One workaround is to provide an extra method in your enum for the number you want:

enum Foo {
  BAR(3),
  BAZ(5);
  private final int val;
  private Foo(int v) { val = v; }
  public int getVal() { return val; }
}

In this situation BAR.ordinal() == 0, but BAR.getVal() == 3.

Leave a Comment