Java: Having trouble declaring an enum with integer constants

后端 未结 3 1986
庸人自扰
庸人自扰 2021-01-19 17:19

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 Dire         


        
相关标签:
3条回答
  • 2021-01-19 17:34

    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.

    0 讨论(0)
  • 2021-01-19 17:39

    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

    • Java Language Guide/Enums - a quick but comprehensive guide to Java enum

    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

    • Java Tutorials/Collections Framework
    • Effective Java 2nd Edition
      • Item 30: Use enum instead of int constants
      • Item 31: Use instance fields instead of ordinals
      • Item 32: Use EnumSet instead of bit fields
      • Item 33: Use EnumMap instead of ordinal indexing

    Related questions

    • Enumerations: why? when? - with examples of EnumSet and EnumMap usage
    0 讨论(0)
  • 2021-01-19 17:49

    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());
      
    0 讨论(0)
提交回复
热议问题