Java unmodifiable array

21,717

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

Another way is to use this function:

Arrays.copyOf(arr, arr.length);
Share:
21,717
Emil
Author by

Emil

☸Java Programmer☸

Updated on September 01, 2020

Comments

  • Emil
    Emil almost 4 years
    final Integer[] arr={1,2,3};
    arr[0]=3;
    System.out.println(Arrays.toString(arr));
    

    I tried the above code to see whether a final array's variables can be reassigned[ans:it can be].I understand that by a final Integer[] array it means we cannot assign another instance of Integer[] apart from the one we have assigned initially.I would like to know if whether it is possible to make the array variables also unmodifiable.

  • Skip Head
    Skip Head almost 14 years
    This is another good reason to use collections instead of arrays.
  • Martin
    Martin about 11 years
    @SkipHead Depends for which target you are programming. Not every Java program runs in a Java EE container on some large mainframe.
  • MuhammadAnnaqeeb
    MuhammadAnnaqeeb over 10 years
    See the latest documentation of Guava's ImmutableList at docs.guava-libraries.googlecode.com/git-history/release/java‌​doc/… as add and addAll methods are now deprecated.
  • tokovach
    tokovach over 3 years
    However, that would introduce extra overhead (stored twice in memory) as the entire array is copied again.