枚举与Java中的int值 [英] Enum with int value in Java

查看:227
本文介绍了枚举与Java中的int值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 枚举Foo 
{
Bar = 0,
Baz = 1,
Fii = 10,
}


解决方案

如果你想要你的枚举的属性,你需要这样定义:

  public enum Foo {
BAR(0),
BAZ(1),
FII(10);

private final int index;

Foo(int index){
this.index = index;
}

public int index(){
return index;
}

}

你会像这样使用:

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

要实现的是枚举只是创建一个类的快捷方式,所以你可以添加任何你想要的类的属性和方法。



如果你不想在您的枚举中定义任何方法,您可以更改成员变量的范围并使其成为 public 但这并不是他们在 Sun网站上的示例


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

enum Foo
{
  Bar = 0,
  Baz = 1,
  Fii = 10,
}

解决方案

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.

这篇关于枚举与Java中的int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆