Enums with static fields

suggest change

If your enum class is required to have static fields, keep in mind they are created after the enum values themselves. That means the following code will result in a NullPointerException (Map and HashMap are in java.util):

enum Example {
    ONE(1), TWO(2);

    static Map<String, Integer> integers = new HashMap<>();

    private Example(int value) {
        integers.put(this.name(), value);
    }
}

A possible way to fix this:

enum Example {
    ONE(1), TWO(2);

    static Map<String, Integer> integers;

    private Example(int value) {
        putValue(this.name(), value);
    }

    private static void putValue(String name, int value) {
        if (integers == null)
            integers = new HashMap<>();
        integers.put(name, value);
    }
}

Do not assign the map in the field declaration. That assignment runs after the enum constants and clears the map:

enum Example {
    ONE(1), TWO(2);

    // this assignment runs after the constants are created and clears the map
    static Map<String, Integer> integers = null;

    private Example(int value) {
        putValue(this.name(), value);
    }

    private static void putValue(String name, int value) {
        if (integers == null)
            integers = new HashMap<>();
        integers.put(name, value);
    }
    // !!this may lead to a NullPointerException!!
    public int getValue(){
        return (Example.integers.get(this.name()));
    }
}

initialisisation:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents