Java unmodifiable array Java unmodifiable array arrays arrays

Java unmodifiable array


This isn't possible as far as I know.

There is however a method Collections.unmodifiableList(..) which creates an unmodifiable view of e.g. a List<Integer>.

If you want to guarantee that not even the creator of the unmodifiable view list will be able to modify the underlying (modifiable) list, have a look at Guava's ImmutableList.


No. The contents of an array can be changed. You can't prevent that.

Collections has various methods for creating unmodifiable collections, but arrays aren't provided for.


The final keyword only prevents changing the arr reference, i.e. you can't do:

final int[] arr={1,2,3}; arr = new int[5]; 

If the object arr is referring to is mutable object (like arrays), nothing prevents you from modifying it.

The only solution is to use immutable objects.