对于这种情况,看起来您可以简单地使用实例字段.
public enum Direction {
NORTH(0x10), WEST(0x18), ...;
private final int code;
Direction(int code) { this.code = code; }
public int getCode() { return code; }
}
Java enum
被实现为对象。它们可以有字段和方法。您还可以选择声明一个带有一些参数的构造函数,并在常量声明中为这些参数提供值。您可以使用这些值来初始化任何声明的字段。
See also
-
Java 语言指南/枚举- 快速而全面的 Java 指南
enum
附录:EnumSet
and EnumMap
请注意,根据这些值的不同,您可能有比实例字段更好的选择。也就是说,如果您尝试设置位字段的值,您应该只使用EnumSet反而。
在 C++ 中,经常会看到两个常量的幂与按位运算作为集合的紧凑表示。
// "before" implementation, with bitwise operations
public static final int BUTTON_A = 0x01;
public static final int BUTTON_B = 0x02;
public static final int BUTTON_X = 0x04;
public static final int BUTTON_Y = 0x08;
int buttonState = BUTTON_A | BUTTON_X; // A & X are pressed!
if ((buttonState & BUTTON_B) != 0) ... // B is pressed...
With enum
and EnumSet
,这可能看起来像这样:
// "after" implementation, with enum and EnumSet
enum Button { A, B, X, Y; }
Set<Button> buttonState = EnumSet.of(Button.A, Button.X); // A & X are pressed!
if (buttonState.contains(Button.B)) ... // B is pressed...
还有EnumMap您可能想要使用。它是Map谁的钥匙是enum
常数。
那么,和以前一样,您可能会遇到这样的情况:
// "before", with int constants and array indexing
public static final int JANUARY = 0; ...
Employee[] employeeOfTheMonth = ...
employeeOfTheMonth[JANUARY] = jamesBond;
现在您可以拥有:
// "after", with enum and EnumMap
enum Month { JANUARY, ... }
Map<Month, Employee> employeeOfTheMonth = ...
employeeOfTheMonth.put(Month.JANUARY, jamesBond);
在爪哇,enum
是一个非常强大的抽象,也可以很好地与 Java 集合框架配合使用。
See also
- Java 教程/集合框架
-
Effective Java 2nd Edition
- 第 30 项:使用
enum
代替int
常量
- 第 31 项:使用实例字段代替序数
- 第 32 项:使用EnumSet而不是位域
- 第 33 项:使用EnumMap而不是顺序索引
相关问题
-
枚举:为什么?什么时候?- 举例说明
EnumSet
and EnumMap
usage