Enum with int value in Java

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

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

    In Java enums are very similar to other classes but the the Java compiler knows to treat a little differently in various situations. So if you want data in them like you seem to you need to have an instance variable for the data and an appropriate constructor.

提交回复
热议问题