Enum with int value in Java

前端 未结 5 2131
旧巷少年郎
旧巷少年郎 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:45

    It is:

    enum Foo
    {
      Bar(0),
      Baz(1),
      Fii(10);
    
      private int index;
    
      private Foo(int index) {
          this.index = index;
      }
    }
    

    Note that to get the value of the enum from the index, Foo.valueOf(1) (*), would not work. You need do code it yourself:

    public Foo getFooFromIndex(int index) {
        switch (index) {
        case 0:
            return Foo.Bar;
        case 1:
            return Foo.Baz;
        case 10:
            return Foo.Fii;
    
        default:
            throw new RuntimeException("Unknown index:" + index);
        }
    }
    

    (*): Enum.valueOf() return the enum from a String. As such, you can get the value Bar with Foo.valueOf('Bar')

提交回复
热议问题