Declaring an ArrayList object as final for use in a constants file
Guava provides ImmutableList
for just about this reason. (Also, it doesn't have the unnecessary space overhead that ArrayList
allocates to make room for future elements which you won't be adding for your application.)
public static final ImmutableList<String> CONSTANTS =
ImmutableList.of("foo", "bar");
You can easily make it public static final
, but that won't stop people from changing the contents.
The best approach is to safely publish the "constant" by:
- wrapping it in an unmodifiable list
- using an instance block to populate it
Resulting in one neat final declaration with initialization:
public static final List<String> list = Collections.unmodifiableList(
new ArrayList<String>() {{
add("foo");
add("bar");
// etc
}});
or, similar but different style for simple elements (that don't need code)
public static final List<String> list =
Collections.unmodifiableList(Arrays.asList("foo", "bar"));