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.
Advertisement
Answer
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));