有没有什么办法,使在Java中普通的数组不变? [英] Is there any way to make an ordinary array immutable in Java?
问题描述
用Google搜索了一下,发现很多code的。但是,任何人给我我想要的。我想打一个普通的数组不可改变的。我想这样的:
Googled for it, found plenty of code. But any of them gave me what I want. I want to make an ordinary array Immutable. I tried this:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class test {
public static void main(String[] args) {
final Integer array[];
List<Integer> temp = new ArrayList<Integer>();
temp.add(Integer.valueOf(0));
temp.add(Integer.valueOf(2));
temp.add(Integer.valueOf(3));
temp.add(Integer.valueOf(4));
List<Integer> immutable = Collections.unmodifiableList(temp);
array = immutable.toArray(new Integer[immutable.size()]);
for(int i=0; i<array.length; i++)
System.out.println(array[i]);
array[0] = 5;
for(int i=0; i<array.length; i++)
System.out.println(array[i]);
}
}
但它不工作,我可以指定一个5到数组[0] ...有没有什么办法让这阵不变?
But it doesnt work, I CAN assign a 5 into array[0] ... Is there any way to make this array immutable?
推荐答案
如果你想的使用它作为一个数组的,你不能。
If you want to use it as an array, you can't.
您必须为它创建一个包装,让你扔在,比方说,的.set()
异常,但无缠绕量将允许你抛出异常的:
You have to create a wrapper for it, so that you throw an exception on, say, .set()
, but no amount of wrapping around will allow you to throw an exception on:
array[0] = somethingElse;
当然,元素的不变性是另一回事完全!
Of course, immutability of elements is another matter entirely!
注意:标准异常抛出了不支持的操作是恰当地命名为 UnsupportedOperationException异常
;因为它未被选中,你不需要声明它在你的方法的抛出
子句。
NOTE: the standard exception to throw for unsupported operations is aptly named UnsupportedOperationException
; as it is unchecked you don't need to declare it in your method's throws
clause.
这篇关于有没有什么办法,使在Java中普通的数组不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!