Immutable array in Java

ignoramus picture ignoramus · Sep 13, 2010 · Viewed 104.8k times · Source

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.

Answer

Jason S picture Jason S · Sep 13, 2010

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));