How to use enumMap in java

27,831

Solution 1

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]

Solution 2

You forgot to initialize EnumMap in your code.

You could initialize it within main before x.put something like:

x = new EnumMap<Value, Integer>(Value.class);

And use your array like:

int[] myArray = new int[x.get(Value.SIZE)];

Solution 3

public static EnumMap<Value, Integer> x = new EnumMap<Value, Integer>(Value.class);
Share:
27,831
Shadow
Author by

Shadow

Learning C++ / Sort of learning Java

Updated on July 18, 2022

Comments

  • Shadow
    Shadow almost 2 years

    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?