Java中的不可变数组 [英] Immutable array in Java

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

问题描述

Java 中的原始数组有不可变的替代品吗?制作一个原始数组 final 实际上并不会阻止一个人做类似

Is there an immutable alternative to the primitive arrays in Java? Making a primitive array final doesn't actually prevent one from doing something like

final int[] array = new int[] {0, 1, 2, 3};
array[0] = 42;

我希望数组的元素是不可更改的.

I want the elements of the array to be unchangeable.

推荐答案

不适用于原始数组.您需要使用 List 或其他一些数据结构:

Not with primitive arrays. You'll need to use a List or some other data structure:

List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));

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

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