Enum with int value in Java

前端 未结 5 2130
旧巷少年郎
旧巷少年郎 2020-12-05 06:17

What\'s the Java equivalent of C#\'s:

enum Foo
{
  Bar = 0,
  Baz = 1,
  Fii = 10,
}
5条回答
  •  孤城傲影
    2020-12-05 06:40

    If you have a contiguous range of values, and all you need is the integer value, you can just declare the enum minimally:

    public enum NUMBERZ {
            ZERO, ONE, TWO
    }
    

    and then obtain the int value as follows:

    int numberOne = NUMBERZ.ONE.ordinal();
    

    However, if you need a discontiguous range (as in your example, where you jump from 1 to 10) then you will need to write your own enum constructor which sets your own member variable, and provide a get method for that variable, as described in the other answers here.

提交回复
热议问题