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:
用Google搜索,找到了大量的代码。但是他们中的任何一个都给了我想要的东西。我想制作一个普通的数组永恒。我试过这个:
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]);
}
}
But it doesnt work, I CAN assign a 5 into array[0] ... Is there any way to make this array immutable?
但它不起作用,我可以将5分配给数组[0] ...有没有办法使这个数组不可变?
5
If you want to use it as an array, you can't.
如果要将其用作数组,则不能。
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:
你必须为它创建一个包装器,这样就可以在.set()上抛出一个异常,但是没有任何包装可以让你在以下方面抛出异常:
array[0] = somethingElse;
Of course, immutability of elements is another matter entirely!
当然,元素的不变性完全是另一回事!
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.
注意:抛出不支持的操作的标准异常恰当地命名为UnsupportedOperationException;因为它未经检查,所以您不需要在方法的throws子句中声明它。
3
It's impossible with primitive arrays.
原始数组是不可能的。
You will have to use the Collections.unmodifiableList()
as you already did in your code.
您必须像在代码中一样使用Collections.unmodifiableList()。
1
You can also use Guava's ImmutableList, a high-performance, immutable, random-access List implementation that does not permit null elements. Unlike Collections.unmodifiableList(java.util.List)
, which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change.
您还可以使用Guava的ImmutableList,这是一种高性能,不可变的随机访问List实现,不允许使用null元素。与Collections.unmodifiableList(java.util.List)不同,Collections.unmodifiableList(java.util.List)是一个可以更改的单独集合的视图,ImmutableList的实例包含其自己的私有数据,并且永远不会更改。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/06/15/6763e7b022bc9dcb6c4a9097f3db131c.html。