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

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

问题描述

Java 与 C# 的等价物是什么:

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

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

推荐答案

如果你想要你的 enum 的属性,你需要像这样定义它:

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; 
    }

}

你会这样使用它:

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

需要注意的是,enum 只是创建类的快捷方式,因此您可以向类添加任何您想要的属性和方法.

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.

如果您不想在 enum 上定义任何方法,您可以更改成员变量的范围并使它们 public,但这不是他们所做的在Sun 网站上的示例中.

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天全站免登陆