declaring an array
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?
int[] a = {1,2,3};
final int[] b = a;
a[0] = 10; // should this be legal?
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?
final int[][] a = {{1,2}, {3,4}};
a[1][1] = 5;
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 simpler const
, much like Java is a simpler C++. Let's keep it simple, shall we?