尝试从Array.asList返回的列表中删除UnsupportedOperationException [英] UnsupportedOperationException when trying to remove from the list returned by Array.asList

查看:132
本文介绍了尝试从Array.asList返回的列表中删除UnsupportedOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用列表来保存通过调用 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:


返回由指定数组支持的固定大小的列表。 p>

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 Collections Library (或,发布时).google.com / p / guava-libraries /rel =noreferrer> Guava 。然后,您可以使用:

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆