what is the sense of final ArrayList?
Solution 1
But what is effect making it's final?
This means that you cannot rebind the variable to point to a different collection instance:
final List<Integer> list = new ArrayList<Integer>();
list = new ArrayList<Integer>(); // Since `list' is final, this won't compile
As a matter of style, I declare most references that I don't intend to change as final
.
I still can add to ArrayList new elements, remove elements and update it.
If you wish, you can prevent insertion, removal etc by using Collections.unmodifiableList()
:
final List<Integer> list = Collections.unmodifiableList(new ArrayList<Integer>(...));
Solution 2
It just means that you can't re-assign its reference. Attempting to do something like the below will lead to compiler error.
final List<String> list = new ArrayList<String>();
list = new LinkedList<String>();
^
Compiler error here
If you really want an immutable list, you should use the Collections.unmodifiableList()
method.
Solution 3
You won't be able to modify its reference using new ArrayList
for example.
Solution 4
final
has a lot of consequences under multi threading.
- JMM clearly defines a
final
field's initialization completion is guaranteed.
What's not clearly defined is:
- Compilers are free to reorder them across memory barriers.
- Compilers can always read a cached copy.
Solution 5
Making the variable final
makes sure you cannot re-assign that objest reference after it is assigned. As you mention you can still use that lists methods to make changes.
If you combine the final
keyword with the use of Collections.unmodifiableList, you ge the behaviour you are probably trying to achieve, for instance:
final List fixedList = Collections.unmodifiableList(someList);
This has as result that the list pointed to by fixedList
cannot be changed. Beware however that it can still be change through the someList
reference (so make sure it is out of scope after this asignment.)
WelcomeTo
Updated on August 13, 2021Comments
-
WelcomeTo almost 3 years
Which advantages/disadvantages we can get by making ArrayList (or other Collection) final? I still can add to ArrayList new elements, remove elements and update it. But what is effect making it's final?
-
Vishy about 12 years+1 Using final fields can improve clarity as classes can be quite long. I don't use final in methods so much as I try to break up long methods.
-
Coder over 3 yearshow does
final
improve clarity?