Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

java - 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???

question from:https://stackoverflow.com/questions/9285011/declaring-an-arraylist-object-as-final-for-use-in-a-constants-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...