Java never had immutable primitive arrays. However Java does have an immutable List
or Map
or other collection classes and of course final
primitive fields and variables. In Java if you try to make an Object
or array final
you only make the reference final
. The reference will only point to the same actual object but this does not make the underlying object immutable.
One advantage of immutable arrays would be not needing to create defensive copies because the array could be immutable anyway and could be trivially implemented in syntax:
final int[final] array = new int[final]{1, 2, 3, 4};
Is there a particular technical reason for allowing primitives and references to be made immutable but not arrays? What are the specific less obvious implications to immutable arrays that caused them to be left out of Java and why do they apply to arrays specifically but not primitives? What language or implementation features or mechanics are incompatible with immutable arrays and how so? What other parts of the language would not 'add up' if there were immutable primitive arrays?
final
makes the variable immutable, not the value it holds. Primitive values are always immutable. Objects may or may not be immutable depending on their implementation. Arrays are "special" in Java. They are not instances of classes and cannot be inherited, so there is no place to put metadata that would distinguish an immutable array from a regular array. Array item access cannot be overridden but is directly compiled to special-purpose bytecode instructions. In short, it is not realistic to change how arrays work, since they are baked into the fundamentals of the language.