Java unmodifiable array

给你一囗甜甜゛ 提交于 2019-11-28 11:00:19
Andre Holzner

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.

Another way is to use this function:

Arrays.copyOf(arr, arr.length);

The keyword 'final' applies to only the references (pointer to the memory location of the object in the heap). You can't change the memory address (location) of the object. Its upto your object how it internally handles the immutability.

Added, although int is a primitive data type int[] should be treated as a object.

You can't do this

final int a = 5
a = 6

You can do this:

final int[] a = new int[]{2,3,4};
  a[0] = 6;

You can't do this:

final int[] a = new int[]{2,3,4};
 a = new int[]{1,2,3}

To anybody else reading this old question, keep in mind there is also Google Guava's immutable collections. ImmutableList has much stronger performance than Collections.unmodifiableList(), and is arguably safer as it truly is immutable,and not backed by a mutable collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!