My question is regarding declaring an arraylist as final. I know that once I write final ArrayList list = new ArrayList();
I can add, delete objects from this list,
When you say
final ArrayList list = new ArrayList();
this means that the variable list
will always point to the same ArrayList
object. There are two situations in which this can be useful.
list
variable once it has received its value. This can reduce complexity and helps in understanding the semantics of your class/method. In this case you are usually better off by using good naming conventions and reducing method length (the class/method is already too complex to be easily understood).final
in an enclosing scope so that you can access them in the inner class. This way, Java can copy your final
variable into the inner class object (it will never change its value) and the inner class object does not need to worry what happens to the outer class object while the inner class object is alive and needs to access the value of that variable.The second part of your question is about the difference between
ArrayList list = new ArrayList();
and
private static final ArrayList list = new ArrayList();
The difference of course are the modifiers. private
means not visible outside the class, static
means that it is defined on the class level and doesn't need an instance to exist, and final
is discussed above. No modifiers means package-private or default access.