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???
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.
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.
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));
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:
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With