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

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

问题描述

有Java中的基本数组不可改变的选择吗?制作一个基本数组最后实际上并不prevent一个来自做这样的事情。

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.

推荐答案

不带基本数组。你需要使用一个列表或者其他一些数据结构:

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天全站免登陆