Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enumMap in java

Tags:

java

arrays

enums

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?

like image 992
Shadow Avatar asked Oct 14 '14 09:10

Shadow


1 Answers

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]
like image 187
Justin Avatar answered Oct 06 '22 05:10

Justin