Skip to main content
7 of 7
added 96 characters in body
CPlus
  • 1.2k
  • 1
  • 10
  • 26

What prevents Java from having immutable primitive arrays?

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?

CPlus
  • 1.2k
  • 1
  • 10
  • 26