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

发布于 2024-09-15 16:42:30 字数 775 浏览 4 评论 0原文

呃,我对 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
   }

有人可以告诉我我做错了什么吗? 谢谢,

错误如下:

 ----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
                       ^

Urgh, I'm kind of confused on how enums work in Java. In C# and C++ (what I use normally), this seems okay, but Java wants to get mad at me >.>

   enum Direction
   {
      NORTH_WEST = 0x0C,
      NORTH      = 0x10,
      NORTH_EAST = 0x14,
      WEST       = 0x18,
      NONE       = 0x20,
      EAST       = 0x28,
      SOUTH_WEST = 0x24,
      SOUTH      = 0x30,
      SOUTH_EAST = 0x3C
   }

Could someone tell me what I'm doing wrong?
Thanks

Here are the errors:

 ----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
                       ^

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我最亲爱的 2024-09-22 16:42:31

在 Java 中,枚举默认不保存任何其他值。您必须创建一个私有字段来存储它。 如有必要,请尝试

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

   private final int code;
   private Direction(int code) {
       this.code = code;
   }
}

添加吸气剂。

In Java enums don't hold any other values by default. You'll have to create a private field to store one. Try something like this

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

   private final int code;
   private Direction(int code) {
       this.code = code;
   }
}

Add getter if necessary.

被翻牌 2024-09-22 16:42:31

如果您有java 8并且习惯于拥有自己的工具箱。
然后,您可以添加以下工具:

  • Java 8 样式界面

    公共接口 IntEnumInterface
    {
        // 将映射所有应用程序枚举(整数类型)
        最终静态Map enumHelpers = new HashMap();
        // 确保 Enum 名称在您的应用程序中唯一
        默认 String getEnumUniqueName() { return this.getClass().getCanonicalName() + ":" + this.toString(); }
    
        默认 void init(int 值)
        {
            IntEnumInterfaceHelper h = new IntEnumInterfaceHelper(){};
            h.init(值);
            enumHelpers.put(getEnumUniqueName(), h);
        }
    
        // 访问链接的帮助程序以检索整数值
        默认 public int getId() { return enumHelpers.get(getEnumUniqueName()).getValue(); }
    
        // 助手(伪抽象)
        抽象类 IntEnumInterfaceHelper
        {
            私有 int intValue;
            公共无效 init(int 值) { intValue = 值; }
            公共 int getValue() { 返回 intValue; }
        };
    }
    
  • 从现在开始,您可以这样定义枚举:

    公共枚举 RecordStatus 实现 IntEnumInterface
    {
        新(1),处理(2),处理完成(3),TO_DELETE(0);
        记录状态(int id){ init(id); }
    }
    
  • 然后使用以下方式获取枚举数值:

    System.out.println(RecordStatus.NEW.getId());
    System.out.println(RecordStatus.PROCESSING.getId());
    System.out.println(RecordStatus.PROCESS_COMPLETE.getId());
    System.out.println(RecordStatus.TO_DELETE.getId());
    

if you have java 8 and are used to have your own toolbox.
Then, here's kind of tool you can add:

  • Java 8 style interface

    public interface IntEnumInterface
    {
        // Will MAP all your application Enums (of type integer)
        final static Map<String, IntEnumInterfaceHelper> enumHelpers = new HashMap<String, IntEnumInterfaceHelper>();
        // Ensure Enum unique name accross your application
        default String getEnumUniqueName() { return this.getClass().getCanonicalName() + ":" + this.toString(); }
    
        default void init(int value)
        {
            IntEnumInterfaceHelper h = new IntEnumInterfaceHelper(){};
            h.init(value);
            enumHelpers.put(getEnumUniqueName(), h);
        }
    
        // Access the linked helper to retrieve integer value
        default public int getId() { return enumHelpers.get(getEnumUniqueName()).getValue(); }
    
        // helper (pseudo abstract)
        abstract class IntEnumInterfaceHelper
        {
            private int intValue;
            public void init(int value) { intValue = value; }
            public int getValue() { return intValue; }
        };
    }
    
  • From now on, you can define your enums this way:

    public enum RecordStatus implements IntEnumInterface
    {
        NEW(1), PROCESSING(2) ,PROCESS_COMPLETE(3), TO_DELETE(0);
        RecordStatus(int id) { init(id); }
    }
    
  • Then get the enum numeric values with:

    System.out.println(RecordStatus.NEW.getId());
    System.out.println(RecordStatus.PROCESSING.getId());
    System.out.println(RecordStatus.PROCESS_COMPLETE.getId());
    System.out.println(RecordStatus.TO_DELETE.getId());
    
许久 2024-09-22 16:42:31

当只需要连续数字而不需要特定值时的快速方法:

enum PAGE {WATER, FIRE}
static final PAGE[] intToPage = PAGE.values();

用法

int i = PAGE.WATER.ordinal();
PAGE p = intToPage[i];

Quick way when only consecutive numbers without particular values are needed:

enum PAGE {WATER, FIRE}
static final PAGE[] intToPage = PAGE.values();

usage

int i = PAGE.WATER.ordinal();
PAGE p = intToPage[i];
篱下浅笙歌 2024-09-22 16:42:30

对于这种情况,您似乎可以简单地使用实例字段

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

   private final int code;
   Direction(int code)  { this.code = code; }
   public int getCode() { return code; }
}

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...

使用 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...

还有 EnumMap 。这是一个地图 其键是 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);

在 Java 中,enum 是一个非常强大的抽象,它也可以与 Java 集合框架很好地配合使用。

另请参阅

  • Java 教程/集合框架
  • Effective Java 第二版< /em>
    • 第 30 项:使用 enum 代替 int 常量
    • 第 31 项:使用实例字段代替序数
    • 第 32 项:使用 EnumSet而不是位域
    • 第 33 项:使用 EnumMap而不是顺序索引

相关问题

For this scenario, it looks like you can simply use an instance field.

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

   private final int code;
   Direction(int code)  { this.code = code; }
   public int getCode() { return code; }
}

Java enum are implemented as objects. They can have fields and methods. You also have the option of declaring a constructor that takes some arguments, and providing values for those arguments in your constant declaration. You can use these values to initialize any declared fields.

See also


Appendix: EnumSet and EnumMap

Note that depending on what these values are, you may have an even better option than instance fields. That is, if you're trying to set up values for bit fields, you should just use an EnumSet instead.

It is common to see powers of two constants in, say, C++, to be used in conjunction with bitwise operations as a compact representation of a set.

// "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, this can look something like this:

// "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...

There is also EnumMap that you may want to use. It's a Map whose keys are enum constants.

So, where as before you may have something like this:

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

public static final int JANUARY = 0; ...

Employee[] employeeOfTheMonth = ...

employeeOfTheMonth[JANUARY] = jamesBond;

Now you can have:

// "after", with enum and EnumMap

enum Month { JANUARY, ... }

Map<Month, Employee> employeeOfTheMonth = ...

employeeOfTheMonth.put(Month.JANUARY, jamesBond);

In Java, enum is a very powerful abstraction which also works well with the Java Collections Framework.

See also

Related questions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文