Java:在使用整数常量声明枚举时遇到问题

hr.*_*pik 4 java enums

呃,我对如何在Java中使用枚举感到困惑.在C#和C++(我通常使用的)中,这似乎没问题,但是Java想要生我的气.>

   enum Direction
   {
      NORTH_WEST = 0x0C,
      NORTH      = 0x10,
      NORTH_EAST = 0x14,
      WEST       = 0x18,
      NONE       = 0x20,
      EAST       = 0x28,
      SOUTH_WEST = 0x24,
      SOUTH      = 0x30,
      SOUTH_EAST = 0x3C
   }
Run Code Online (Sandbox Code Playgroud)

有人能告诉我我做错了什么吗?谢谢

以下是错误:

 ----jGRASP exec: javac -g Test.java

Test.java:79: ',', '}', or ';' expected
      NORTH_WEST = 0x0C,
                 ^
Test.java:79: '}' expected
      NORTH_WEST = 0x0C,
                  ^
Test.java:80: <identifier> expected
      NORTH      = 0x10,
           ^
Test.java:87: ';' expected
      SOUTH_EAST = 0x3C
                       ^
Run Code Online (Sandbox Code Playgroud)

pol*_*nts 23

对于这种情况,看起来您可以简单地使用实例字段.

public enum Direction {
   NORTH(0x10), WEST(0x18), ...;

   private final int code;
   Direction(int code)  { this.code = code; }
   public int getCode() { return code; }
}
Run Code Online (Sandbox Code Playgroud)

Java enum被实现为对象.他们可以有领域和方法.您还可以选择声明一个带有一些参数的构造函数,并在常量声明中为这些参数提供值.您可以使用这些值初始化任何声明的字段.

也可以看看


附录:EnumSetEnumMap

请注意,根据这些值的不同,您可能拥有比实例字段更好的选项.也就是说,如果您尝试为位字段设置值,则应该使用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...
Run Code Online (Sandbox Code Playgroud)

使用enumEnumSet,这看起来像这样:

// "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...
Run Code Online (Sandbox Code Playgroud)

还有EnumMap你可能想要使用.它的Map键是enum常量.

那么,和以前一样,你可能会有这样的事情:

// "before", with int constants and array indexing

public static final int JANUARY = 0; ...

Employee[] employeeOfTheMonth = ...

employeeOfTheMonth[JANUARY] = jamesBond;
Run Code Online (Sandbox Code Playgroud)

现在你可以拥有:

// "after", with enum and EnumMap

enum Month { JANUARY, ... }

Map<Month, Employee> employeeOfTheMonth = ...

employeeOfTheMonth.put(Month.JANUARY, jamesBond);
Run Code Online (Sandbox Code Playgroud)

在Java中,它enum是一个非常强大的抽象,也适用于Java Collections Framework.

也可以看看

  • Java教程/集合框架
  • 有效的Java第二版
    • 第30项:使用enum而不是int常量
    • 第31项:使用实例字段而不是序数
    • 第32项:使用EnumSet而不是位字段
    • 第33项:使用EnumMap而不是序数索引

相关问题


Nik*_*bak 12

在Java枚举中,默认情况下不保留任何其他值.您必须创建一个私有字段来存储一个.尝试这样的事情

enum Direction {
   NORTH_WEST(0x0C),
   NORTH(0x10),
   ...

   private final int code;
   private Direction(int code) {
       this.code = code;
   }
}
Run Code Online (Sandbox Code Playgroud)

必要时添加吸气剂.