尝试从 Array.asList 返回的列表中删除时出现 UnsupportedOperationException [英] UnsupportedOperationException when trying to remove from the list returned by Array.asList
问题描述
我正在使用 List
来保存通过调用 Array.asList()
方法获得的一些数据.然后我尝试使用 myList.Remove(int i)
方法删除一个元素.但是当我尝试这样做时,我收到了 UnsupportedOperationException
.这是什么原因?我应该如何解决这个问题?
I am using a List
to hold some data obtained by calling Array.asList()
method. Then I am trying to remove an element using myList.Remove(int i)
method. But while I try to do that I am getting an UnsupportedOperationException
. What would be the reason for this? How should I resolve this problem?
推荐答案
Array.asList()
在列表接口中包裹一个数组.该列表仍由数组支持.数组是固定大小的 - 它们不支持添加或删除元素,因此包装器也不能.
Array.asList()
wraps an array in the list interface. The list is still backed by the array. Arrays are a fixed size - they don't support adding or removing elements, so the wrapper can't either.
文档没有尽可能清楚地说明这一点,但他们确实说:
The docs don't make this as clear as they might, but they do say:
返回由指定数组支持的固定大小的列表.
Returns a fixed-size list backed by the specified array.
固定大小"位应该暗示您不能添加或删除元素:)
The "fixed-size" bit should be a hint that you can't add or remove elements :)
尽管有其他方法可以解决此问题(从数组创建新的 ArrayList
的其他方法)而无需额外的库,但我个人建议获取 Google 收藏库(或 番石榴,发布时).然后你可以使用:
Although there are other ways around this (other ways to create a new ArrayList
from an array) without extra libraries, I'd personally recommend getting hold of the Google Collections Library (or Guava, when it's released). You can then use:
List<Integer> list = Lists.newArrayList(array);
我建议这样做的原因是 GCL 总体上是个好东西,非常值得使用.
The reason I'm suggesting this is that the GCL is a generally good thing, and well worth using.
正如评论中所指出的,这需要一个数组的副本;该列表不受原始数组的支持,并且在另一个集合中不会看到任何一个集合中的更改.
As noted in comments, this takes a copy of the array; the list is not backed by the original array, and changes in either collection will not be seen in the other.
这篇关于尝试从 Array.asList 返回的列表中删除时出现 UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!