Java Collections.unmodifiableCollection返回值 List integers=Arrays.asList(1,2); List integers2=Arrays.asList(1,2); 集合整数3=集合。不可修改的集合(整数); 集合。不可修改的集合(整数2); 整数3.加(3); 整数2.加(3);

Java Collections.unmodifiableCollection返回值 List integers=Arrays.asList(1,2); List integers2=Arrays.asList(1,2); 集合整数3=集合。不可修改的集合(整数); 集合。不可修改的集合(整数2); 整数3.加(3); 整数2.加(3);,java,Java,我知道执行integers3.add()将抛出一个不支持的操作异常,但是integers2没有改变实例。我查看了Collections.unmodifiableCollection(Collection..)的源代码,但是integers2的实现也从AbstractList中抛出了一个UnsupportedOperationException。为什么会这样?这不是因为使用了集合。不可修改的集合(integers2)。 这是因为Arrays.asList()返回一个无法更改的固定大小数组。这是as

我知道执行
integers3.add()
将抛出一个不支持的操作异常,但是integers2没有改变实例。我查看了Collections.unmodifiableCollection(Collection..)的源代码,但是integers2的实现也从AbstractList中抛出了一个UnsupportedOperationException。为什么会这样?

这不是因为使用了
集合。不可修改的集合(integers2)。
这是因为Arrays.asList()返回一个无法更改的固定大小数组。这是asList()方法的文档的前几行

看看这些节目

返回的列表实现可选的
集合
方法,但会更改返回列表大小的方法除外。这些方法保持列表不变,并抛出
UnsupportedOperationException

进一步研究表明

确保此集合包含指定的元素(可选操作


由于调用
整数2.add(3)
将更改
整数的大小2
,调用将抛出一个
不支持的操作异常

数组。asList()
返回上记录的固定大小列表,因此您不能对其调用
add()
。将集合设置为不可修改并不意味着它已经不可修改。噢,谢谢,我以前没有意识到Array类下有一个ArrayList,它不会覆盖abstractlist中的add方法
List<Integer> integers = Arrays.asList(1, 2);
List<Integer> integers2 = Arrays.asList(1, 2);
Collection<Integer> integers3 = Collections.unmodifiableCollection(integers);
Collections.unmodifiableCollection(integers2);
integers3.add(3);
integers2.add(3); 
/**
 * Returns a fixed-size list backed by the specified array.  (Changes to
 * the returned list "write through" to the array.)  This method acts
 * as bridge between array-based and collection-based APIs, in
 * combination with {@link Collection#toArray}.  The returned list is
 * serializable and implements {@link RandomAccess}.