Some of the static types prohibited by the Enum initializer

Below is a snippet of code,

public enum Main {

    INSTANCE;

    private final static String STR = "abc";
    private final Map<Integer, Character> map = new HashMap<>();

    private final static int[] NUMS = { 1, 2, 3 };


    private Main() {
        for (int i = 0; i < STR.length(); i++)
            map.put(NUMS[i], STR.charAt(i)); // compiler error!
    }

    public char toChar(int i) {
        return map.get(i);
    }

    public static void main(String[] args) {
        System.out.println(Main.INSTANCE.toChar(2));
    }
}

He released compiler errors below,

illegal reference to static field NUMS from initializer.

Why is it STRallowed staticbut NUMSnot?

+4
source share
2 answers

Enum instances are initialized before all other fields, so you cannot initialize such fields static.

But there is a simple job!

private static class Holder {
    final static int[] NUMS = { 1, 2, 3 };
}

private Main() {
    for (int i = 0; i < STR.length(); i++)
        map.put(Holder.NUMS[i], STR.charAt(i)); // No compiler error!
}

This is an example of Initialization at the request of the owner of the idiom , which exploits the fact that inner classes are fully initialized before the class itself is initialized and guaranteed that JLS is thread safe.

+3
source

:

static , , (§4.12.4).

, , (.. INSTANCE) ( static final), NUMS , null, , , . , enum .

+3

Source: https://habr.com/ru/post/1671967/


All Articles