For this scenario, it looks like you can just use the 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 implemented as objects. They can have fields and methods. You also have the option of declaring a constructor that takes some arguments and provides values ββfor these arguments in your constant declaration. These values ββcan be used to initialize all declared fields.
see also
Application: EnumSet and EnumMap
Note that depending on what these values ββare, you may have an even better option than the instance fields. That is, if you are trying to adjust the values ββfor bit fields, you should just use EnumSet .
It is generally accepted to consider the powers of two constants, for example, in C ++, which will be used in conjunction with bitwise operations in the form of 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 might 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 an EnumMap that you can use. This is a Map whose keys are enum constants.
So where, as before, there might be something like this:
// "before", with int constants and array indexing public static final int JANUARY = 0; ... Employee[] employeeOfTheMonth = ... employeeOfTheMonth[JANUARY] = jamesBond;
Now you can:
// "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 that also works well with the Java Collection Framework.
see also
- Tutorials / Java Collections
- Effective Java 2nd Edition
- Point 30: use
enum instead of int constants - Item 31: Use instance fields instead of ordinals
- Item 32: Use
EnumSet Instead of Bit Fields - Paragraph 33: Use
EnumMap instead of Indexing
Related Questions
- Enumerations: why? when? - with examples of using
EnumSet and EnumMap