Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

java - UnsupportedOperationException when trying to remove from the list returned by Array.asList

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :)

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);

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...