To initialize a static final
fields that require using more than a single expression, a static
initializer can be used to assign the value. The following example initializes a unmodifiable set of String
s:
public class MyClass {
public static final Set<String> WORDS;
static {
Set<String> set = new HashSet<>();
set.add("Hello");
set.add("World");
set.add("foo");
set.add("bar");
set.add("42");
WORDS = Collections.unmodifiableSet(set);
}
}