How do you use enumMap in java? I want to use an enumMap to get constant named values that go from 0 to n where n is size. But I don't understand the description on the oracle site > EnumMap.
I tried to use one here
package myPackage;
import java.util.EnumMap;
public class Main{
public static enum Value{
VALUE_ONE, VALUE_TWO, SIZE
}
public static EnumMap<Value, Integer> x;
public static void main(String[] args){
x.put(Value.VALUE_ONE, 0);
x.put(Value.VALUE_TWO, 1);
x.put(Value.SIZE, 2);
int[] myArray = new int[SIZE];
}
}
This doesn't work. How are you supposed to use an enumMap?
is there also a way to do without x.put(Value.VALUE_ONE, 0);
for every single element in the enum?
Don't attempt to store the size in the enumeration, EnumMap
has a size
method for that.
public static enum Value{
VALUE_ONE, VALUE_TWO
}
Also, enumeration types have a static method values
that you can use to get an array of the instances. You can use that to loop through and add them to the EnumMap
public static void main(String[] args){
for(int i = 0; i < Value.values().length ; i++) {
x.put(Value.values()[i], i);
}
int[] myArray = new int[x.size()];
}
You also need to be sure to initialize the EnumMap
otherwise you will have a NullPointerException
:
public static EnumMap<Value, Integer> x = new EnumMap<>(Value.class);
If all you're trying to do is retrieve enumeration values by indices then you don't need an EnumMap
at all. That's only useful if you are trying to assign arbitrary values.
You can get any enumeration by index using the values
method:
Value.values()[INDEX]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With