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);
Run Code Online (Sandbox Code Playgroud)
我知道执行integers3.add()会抛出 UnsupportedOperationException,但 integers2 没有改变实例。我查看了 Collections.unmodifiableCollection(Collection ..) 的源代码,但是 integers2 的实现也从 AbstractList 抛出了 UnsupportedOperationException。为什么是这样?
这不是因为使用Collections.unmodifiableCollection(integers2);. 这是因为 Arrays.asList() 返回一个无法更改的固定大小数组。这是 asList() 方法文档的前几行。
/**
* 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}.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |