How do you use an enum for an array subscript?
enum {VALUE_ONE, ... , SIZE};
int[] x = new int[SIZE];
Here's the code. It doesn't look like good practice, though.
int[] x = new int[EnumClass.values().length];
You can then access the element by ordinal()
int val = x[enumVar.ordinal()];
Still doesn't look like good practice.
Consider using Map<EnumClass, AtomicInteger> like EnumMap<EnumClass, AtomicInteger>. Why atomic integer? because it can have it's value modified instead of assigning a new instance all the time (at the cost of possibly unnecessary synchronization). That's a different issue though.
Map<Enum, AtomicInteger>? You have EnumMap designed for enums. I would not depend on enum's ordinal value for any data structure, since it depends entirely on the definition order. Suppose you save the array, modify the enum, and try to read the array. It'll be a problem.Use an EnumMap - it was intended for just this case.
enum Value {
VALUE_ONE, ... , VALUE_LAKH
}
Map<Value, Integer> x = new EnumMap<>();
x.put(Value.VALUE_ONE, 13);
Internally uses an array (Integer[]). The only disadvantage is using Integer instead of int. And assumedly java 9 or 10 will introduce primitive generic types (List<int> and such).
BTW EnumSet exists too, and is as efficient as BitSet.
You can use: int[] x = new int[SIZE.ordinal()]; int var = x[SOME_VALUE.ordinal()];
Its position in its enum declaration, where the initial constant is assigned an ordinal of zero.
Or set special number for each enum elements. like:
enum A {
VALUE_ONE(0),
SIZE(1),
;
int value;
private A( int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
int[] x = new int[A.SIZE.getValue()];
int var = x[A.VALUE_ONE.getValue()];
VALUE_ONE(0), VALUE_TWO(1), I used these but they both resulted in 0 when printed when SIZE(2)int[] x = new int[A.SIZE.getValue()]; int var1 = x[A.VALUE_ONE.getValue()];// var1 == 0 int var2 = x[A.VALUE_TWO.getValue()];// var2 == 0 You mean that?var = x[A.VALUE_ONE.getValue()] and then printed var. I set var equal to the same thing but VALUE_TWO this time and they both printed out 0[0, 0]
values()to get all its values.and useordinal()to get it's position in enum.