Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 823
Raghu Avatar asked Feb 14 '12 22:02

Raghu


People also ask

Can we declare ArrayList as final in Java?

Output Explanation: The array arr is declared as final, but the elements of an array are changed without any problem. Arrays are objects and object variables are always references in Java. So, when we declare an object variable as final, it means that the variable cannot be changed to refer to anything else.

How do you make an ArrayList final?

The final arrayList can still be modified, refer to the example below and run it to see for your self. As you can see, the main method is adding (modifying) the list. So the only thing to note is that the "reference" to the object of the collection type can't be re-assigned to another such object.

How do you initialize a final ArrayList in Java?

ArrayList Initialization using Arrays. asList() method This is a perfect way to initialize an ArrayList because you can specify all the elements inside asList() method. Syntax: ArrayList<Type> obj = new ArrayList<Type>( Arrays. asList(Object o1, Object o2, Object o3, ....so on));


1 Answers

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")); 
like image 123
Bohemian Avatar answered Oct 16 '22 07:10

Bohemian