Declaring an ArrayList object as final for use in a constants file

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

Leave a Comment