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?
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.
A List with final keyword, still you can add as well as remove. But you cannot copy the list into another list.
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However, the data within the object can be changed.
In Java, we know that String objects are immutable means we can't change anything to the existing String objects. final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g).
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>(...));
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.
You won't be able to modify its reference using new ArrayList
for example.
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.)
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