Is it a good practice to use static initializers?

450 Views Asked by At

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?

1

There are 1 best solutions below

2
Mureinik On BEST ANSWER

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");