Java 不可修改数组 [英] Java unmodifiable array

查看:96
本文介绍了Java 不可修改数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我尝试了上面的代码来查看是否可以重新分配最终数组的变量[ans:它可以].我理解最终的 Integer[] 数组意味着我们不能分配另一个实例Integer[] 除了我们最初分配的那个.我想知道是否可以使数组变量也不可修改.

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.

推荐答案

据我所知,这是不可能的.

This isn't possible as far as I know.

然而有一种方法 Collections.unmodifiableList(..) 它创建了一个不可修改的视图,例如一个 List.

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

如果您想保证即使是不可修改视图列表的创建者也无法修改底层(可修改)列表,请查看 Guava 的 ImmutableList.

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.

这篇关于Java 不可修改数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆