I asked: What prevents Java from having immutable primitive arrays? a while back and got an answer: Because immutable primitive arrays would typically require checking some immutable flag every time a write attempt is made, slowing down performance.
But I just thought, variables and references themselves can be made read-only (final
). Yet they do not have a immutable flag associated with them (as far as I know), rather, they are checked at compile time. Would having a similar mechanism for immutable arrays be possible?
For example, a mutable array reference could be converted to an immutable one but not vice versa, and thus any attempt made to write to an immutable array could be rejected at compile time, similar to other final
items? Or are there edge cases that would make that not work out somehow?
While this is technically having immutable views to arrays rather than actual immutable arrays themselves, is there any difference in practice between a 'true' immutable array and an array created as an immutable view, so no non-immutable view exists? Either way, the array cannot and will not be modified.