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

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

问题描述

什么是Java的等效C#的:

 枚举富
{
  栏= 0,
  巴兹= 1,
  FII = 10,
}


解决方案

如果你想为你的属性枚举您需要定义它是这样的:

 公共枚举富{
    BAR(0),
    BAZ(1),
    FII(10);    私人最终诠释指数;    美孚(INT指数){
        this.index =指数;
    }    公众诠释指数(){
        返回指数;
    }}

您会使用这样的:

 公共静态无效的主要(字串[] args){
    为(美孚F:Foo.values​​()){
       System.out.printf(%s已索引%D%N,F f.index());
    }
}

要认识到的一点是,枚举仅仅是创建一个类的快捷方式,这样你就可以添加任何属性和你想要的类方法。

如果你不想来定义你的枚举你可以改变成员变量的作用域的任何方法,使它们公共,但是这不是他们在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天全站免登陆