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
final
has a lot of consequences under multi threading.
final
field's initialization completion is guaranteed.What's not clearly defined is:
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>(...));
You won't be able to modify its reference using new ArrayList
for example.
You cannot rebind it to a different collection as aix said.
Example: In conjuction with immutable list implementation you get safe members which you can make public available.
Example: When you rely on that reference does not change you need final. This is true in synchronization scenarios for example.
There may be much more examples. It is good style to declare members final if you do not intend to change the reference at all.
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.)
Essentially what you are trying to achieve here is making the list immutable I guess. However when you mark the list reference final it implies that the reference cant be pointed to any other list object other than this.
If you want a final (immutable) ArrayList go for Collections class's utility method Collections.unmodifaibleList( list ) instead.