java int枚举和int,枚举与Java中的int值

这篇博客探讨了如何在Java中实现类似于C#的枚举(enum)功能。作者指出,Java中的enum实际上是一种简化的类,可以添加属性和方法。文章通过示例展示了如何定义带有索引的枚举,并提供了枚举类的使用方法,包括如何通过values()方法遍历枚举实例。
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值