Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java unmodifiable array

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.

like image 1000
Emil Avatar asked Sep 17 '10 18:09

Emil


People also ask

What is an unmodifiable list in Java?

The unmodifiableList() method of java. util. Collections class is used to return an unmodifiable view of the specified list. This method allows modules to provide users with “read-only” access to internal lists.

How do you make an array unchangeable?

There is one way to make an immutable array in Java: final String[] IMMUTABLE = new String[0]; Arrays with 0 elements (obviously) cannot be mutated.

Are arrays asList Unmodifiable?

asList() method. Arrays. asList() method returns a fixed-size list backed by the specified array. Since an array cannot be structurally modified, it is impossible to add elements to the list or remove elements from it.


1 Answers

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.

like image 64
Andre Holzner Avatar answered Sep 17 '22 01:09

Andre Holzner