Enum with int value in Java

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

    If you want attributes for your enum you need to define it like this:

    public enum Foo {
        BAR (0),
        BAZ (1),
        FII (10);
    
        private final int index;   
    
        Foo(int index) {
            this.index = index;
        }
    
        public int index() { 
            return index; 
        }
    
    }
    

    You'd use it like this:

    public static void main(String[] args) {
        for (Foo f : Foo.values()) {
           System.out.printf("%s has index %d%n", f, f.index());
        }
    }
    

    The thing to realise is that enum is just a shortcut for creating a class, so you can add whatever attributes and methods you want to the class.

    If you don't want to define any methods on your enum you could change the scope of the member variables and make them public, but that's not what they do in the example on the Sun website.

提交回复
热议问题