CopiesList.addAll方法抛出UnsupportedOperationException [英] CopiesList.addAll method throws UnsupportedOperationException
问题描述
List<String> hi = Collections.nCopies(10, "Hi");
List<String> are = Collections.nCopies(10, "Are");
hi.addAll(are);
hi.forEach(System.out::println);
输出
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractCollection.addAll(Unknown Source)
at com.practice.java8.lambdaexp.Test.main(Test.java:14)
我认为AbstractList.add()在JDK中没有实现.这就是为什么它不起作用.
I think AbstractList.add() doesn't have implementation in JDK. That is why it's not working.
但是,如果我使用CopiesList对象创建一个新的ArrayList对象,它将起作用,因为它将具有适当的add()实现.
But if I create a new ArrayList object using a CopiesList object it works, because it will have a proper add() implementation.
我的问题是:为什么 CopiesList
没有正确的addAll实现?
My question is: Why doesn't CopiesList
have a proper implementation for addAll?
推荐答案
Collections.nCopies
返回一个不变的 List
,因此您不能向其中添加任何内容:
Collections.nCopies
returns an immutable List
, so you can't add anything to it:
返回一个不可变列表,该列表由指定对象的n个副本组成.
Returns an immutable list consisting of n copies of the specified object.
它返回一个不变的 List
,因为它仅包含您传递给其构造函数的元素的单个引用:
It returns an immutable List
since it only contains a single reference of the element you pass to its constructor:
新分配的数据对象很小(它包含对该数据对象的单个引用).
这样做是为了提高性能和存储要求- Collections.nCopies(10,"Hi")
和 Collections.nCopies(10000000,"Hi")
占据相同的空间.
This is done for the benefit of performance and storage requirements - Collections.nCopies(10, "Hi")
and Collections.nCopies(10000000, "Hi")
occupy the same amount of space.
因此,将其实现为可变列表将非常困难.如果没有为该元素分配存储空间,如何将第 10000
个元素设置为某个新值?
Therefore it would be very difficult to implement it as a mutable List. How would you set, for example, the 10000
'th element to some new value if there's no storage allocated for that element?
如果需要包含相同对象副本的可变列表,则必须将不可变列表传递给某些可变列表构造函数:
If you need a mutable List that contains copies of the same object, you have to pass the immutable List to some mutable List constructor:
List<String> mutable = new ArrayList<>(Collections.nCopies(10, "Hi"));
这篇关于CopiesList.addAll方法抛出UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!