Why won't declaring an array final make it immutable in Java? Doesn't declaring something final mean it can't be changed?
From question related to immutable array it's clear that declaring an array final doesn't make it unchangeable.
The following is possible.
final int[] array = new int[] {0, 1, 2, 3};
array[0] = 42;
My question is: What is the function of declaring final here then?
final
is only about the reference that is marked by it; there is no such thing as an immutable array in Java. When you sayyou won't be allowed to say
later on. That's all what
final
is about. More generally, ensuring that an object is immutable is often hard work and full of a range of subtleties. The language itself doesn't give much to this end out of the box.Like everyone commented, declaring it final will not let you assign another array to your variable. Read more here
The array itself will retain it's properties same as before.
Here you are making a object reference
final
, not a primitive. (Arrays are special Java objects, too.) Making a referencefinal
means that you cannot make it refer something else once it is initialized. But of course you can change the state of an object referred by a final variable.In Java, we declare variables, and create objects (such as arrays). These actions are independent; we can declare a variable without creating an object, and create an object without declaring a variable.
Immutability is a property of an object, while final is a property of a variable. An object may be referred to by several variables. Which variable should govern immutability of the array object?
If we permit this, the supposedly immutable value of
b[0]
has been changed. But how can the compiler prevent this? By making it impossible to assign a non-final to a final reference? How would I initialize the array, then? I couldn't do so in a loop ...And: What does it even mean for an array to be immutable? For instance, should the following compile?
C++ solves this by permitting
const
to be specified (or omitted) for each level of indirection. In Java, final can be specified (or omitted) once per variable. Yes,final
is a simplerconst
, much like Java is a simpler C++. Let's keep it simple, shall we?final
means you can't change the reference - ie you can't assign another array to that field."Immutable" means you can't change the contents of the array -
final
has no effect on that.As your code shows, you can assign a value to one of the elements of the array, which doesn't change the reference to the array
It means that a new instance of the object would not be allowed.