Storing integer values as constants in Enum manner in java
Well, you can't quite do it that way. PAGE.SIGN_CREATE
will never return 1; it will return PAGE.SIGN_CREATE
. That's the point of enumerated types.
However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:
public enum PAGE{
SIGN_CREATE(0),
SIGN_CREATE_BONUS(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);
private final int value;
PAGE(final int newValue) {
value = newValue;
}
public int getValue() { return value; }
}
And then you call PAGE.SIGN_CREATE.getValue()
to get 0.
The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).
In almost all cases I suggest using an EnumMap
instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).
private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
pageIndexes.put(Page.SIGN_CREATE, 1);
//etc., ...
int createIndex = pageIndexes.get(Page.SIGN_CREATE);
It's typically incredibly efficient, too.
Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.
Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap
instead of ordinal indexing.