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

Raghu picture Raghu · Feb 14, 2012 · Viewed 90.8k times · Source

I am generating an ArrayList of objects. Following is the code

ArrayList someArrayList = new ArrayList();

Public ArrayList getLotOfData()
{
ArrayList someData = new ArrayList();
return someData; 
}


someArrayList = eDAO.getLotOfData();

Once I have this ArrayList object "someArrayList", I would like to declare it public and final and store it in a Constants file so that it can be accessed globally. Is there a way I can do that? If I declare an Arraylist object public and final, then I would not be able to reassign any values to it. I tried the following

public final ArrayList anotherArrayList = new ArrayList();

anotherArrayList.addAll(someArrayList);

I had hoped to store this "anotherArrayList" as a global ArrayList object and use it, but this returns a nullpointer exception. I want to use it just like a String constant "ConstantsFile.anotherArrayList". Any ideas???

Answer

Bohemian picture Bohemian · Feb 14, 2012

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