javastatic-initializationstatic-initializer

Is it a good practice to use static initializers?


Is there any alternative to static initializers in Java?

Just a random example:

private static List<String> list;

static {
    list = new ArrayList<>();
    list.add("foo")
}

Doesn't it make debugging harder?


Solution

  • If you need a static list you will need to initialize it **somewhere*. A static initializer is a fair choice, although in this example, you can trim it down to a one liner:

    private static List<String> list = new ArrayList<>(Arrays.asList("foo"));
    

    Or, if this list shouldn't be modified during the program's lifetime, ever shorter:

    private static final List<String> list = Collections.singletonList("foo");
    

    Or as noted in the comment, in Java 9 and above:

    private static final List<String> list = List.of("foo");