我可以在 Java 中设置枚举起始值吗? [英] Can I set enum start value in Java?
本文介绍了我可以在 Java 中设置枚举起始值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用枚举来创建一些常量:
I use the enum to make a few constants:
enum ids {OPEN, CLOSE};
OPEN 值为零,但我想要它为 100.这可能吗?
the OPEN value is zero, but I want it as 100. Is it possible?
推荐答案
Java 枚举与 C 或 C++ 枚举不同,后者实际上只是整数的标签.
Java enums are not like C or C++ enums, which are really just labels for integers.
Java 枚举的实现更像是类 - 它们甚至可以有多个属性.
Java enums are implemented more like classes - and they can even have multiple attributes.
public enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
最大的区别在于它们类型安全,这意味着您不必担心将 COLOR 枚举分配给 SIZE 变量.
The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.
参见 http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html 了解更多.
这篇关于我可以在 Java 中设置枚举起始值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文