Raghu Raghu - 1 month ago 11
Java Question

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

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

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