kooyee ‘s blog

开源软件, 众人努力的结晶, 全人类的共同财富
posts - 103, comments - 55, trackbacks - 0, articles - 66
   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理
常常使用Arrays.asLisvt()后调用add,remove这些method时出现java.lang.UnsupportedOperationException异常。这是由于:

Arrays.asLisvt() 返回java.util.Arrays$ArrayList, 而不是ArrayList。Arrays$ArrayList和ArrayList都是继承AbstractList,remove,add等method在AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。ArrayList override这些method来对list进行操作,但是Arrays$ArrayList没有override remove(int),add(int)等,所以throw UnsupportedOperationException。

解决方法是使用Iterator,或者转换为ArrayList
List list = Arrays.asList(a[]);
List arrayList 
= new ArrayList(list);


参考

When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

If you want a mutable list built from your array you will have to loop over the array yourself and add each element into the list in turn.

Even then your code won't work because you'll get an IndexOutOfBoundsException as you remove the elements from the list in the for loop. There are two options: use an Iterator which allows you to remove from the list as you iterate over it (my recommendation as it makes the code easier to maintain) or loop backwards over the loop removing from the last one downwards (harder to read).

You are using AbstractList. ArrayList and Arrays$ArrayList are both types of AbstractList. That's why you get UnsupportedOperationException: Arrays$ArrayList does not override remove(int) so the method is called on the superclass, AbstractList, which is what is throwing the exception because this method is not implemented on that class (the reason being to allow you to build immutable subclasses).


评论

# re: 『Java』java.lang.UnsupportedOperationException at java.util.AbstractLis[未登录]  回复  更多评论   

2009-08-15 11:12 by 哈哈
讲解方法很经精确
喜欢这种讲解风格

# re: 『Java』java.lang.UnsupportedOperationException at java.util.AbstractLis  回复  更多评论   

2009-09-03 10:02 by javaisgod
good

# re: 『Java』java.lang.UnsupportedOperationException at java.util.AbstractLis  回复  更多评论   

2009-09-09 11:55 by kellyzly
顶,我的问题解决了,谢谢

# re: 『Java』java.lang.UnsupportedOperationException at java.util.AbstractLis  回复  更多评论   

2010-08-18 17:22 by 冬天鸡鸡好冷
api 的设计多此一举还搞个内部类

只有注册用户登录后才能发表评论。


网站导航: