Java8-如何添加列表< lt; string>>列表< lt; string>>
我有两个 list< list< string>
,并希望将它们串联。
这是我的代码:
List<List<String>> a = Arrays.asList(Arrays.asList("a", "b", "c"));
List<List<String>> b = Arrays.asList(Arrays.asList("d", "e", "f"));
a.addAll(b);
但是,它不起作用并引发异常。
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
下面的代码有效:
List<List<String>> a = new ArrayList<>();
a.add(Arrays.asList("a", "b", "c"));
List<List<String>> b = new ArrayList<>();
b.add(Arrays.asList("d", "e", "f"));
a.addAll(b);
这里有什么区别?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您尝试使用
a.addall(b)
只要 exter Lista
是可变的,并且您不介意修改它。可变的外部列表:
不变的外部列表
如果要保留前
a
和b
列表和/或产生一个新的,使用 java-stream :结果
两种方式共享相同的输出:
内部列表是否不可变,对于这种组合而言并不重要。
Your attempt with
a.addAll(b)
works as long as the outer lista
is mutable and you don't mind to modify it.Mutable outer list:
Immutable outer list
In case you want to preserve the former
a
andb
lists and/or yield a new one, use java-stream:Result
Both ways share the same output:
Whether the inner lists are immutable or not doesn't matter for such combining.
您的代码不起作用,因为
arrays.aslist()
返回https://docs.oracle.com/en/java/javase/17/docs/api/java.base.base.base/java/java/java/util/arrays.html.html#aslist( t ...)
这意味着,当您尝试添加更多元素时,数组中没有代表
list
的空间;因此抛出unsupportedOperationException
。如果要使用特定元素构建
list
,并且还可以扩展其大小,则应通过提供aslist()
aslist()<的列表来使用类'转换构造函数/代码>方法。
这样,您的外部和内部列表都将以实际的
list
行为,而无需在超过原始大小的情况下扔UnsupportedOperationException
。Your code doesn't work because the
Arrays.asList()
returnshttps://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Arrays.html#asList(T...)
This means that when you try to add further elements, there is no space within the array representing the
List
; thus throwing anUnsupportedOperationException
.If you want to build
List
with specific elements and also be able to extend its size, then you should employ the class' Conversion Constructor by providing to it the lists returned by theasList()
method.This way, both your outer and inner lists will behave as an actual
List
without throwing anUnsupportedOperationException
when exceeding the original size.您可以避免使用addall函数并通过B进行迭代,并添加到如下所示的类似:
You could avoid using the addAll function and iterate through b and add to a like shown below: