Can I specify ordinal for enum in Java?

前端 未结 7 2052
时光说笑
时光说笑 2020-12-01 05:45

The ordinal() method returns the ordinal of an enum instance.
How can I set the ordinal for an enum?

7条回答
  •  时光说笑
    2020-12-01 06:50

    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.

提交回复
热议问题