Skip to content

Immutable array in Java

Is there an immutable alternative to the primitive arrays in Java? Making a primitive array final doesn’t actually prevent one from doing something like

final int[] array = new int[] {0, 1, 2, 3};
array[0] = 42;

I want the elements of the array to be unchangeable.



Not with primitive arrays. You’ll need to use a List or some other data structure:

List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));
User contributions licensed under: CC BY-SA
5 People found this is helpful