使用asList 不能进行add(),remove()操作,如何解决?

来源:互联网 发布:sql数据库管理下载 编辑:程序博客网 时间:2024/06/01 07:36

问题情形:

使用List<Integer> temp = Arrays.asList(1,2,3,4,5);

Iterator<Integer> it = temp.iterator();
while(it.hasNext()){
System.out.println(it.next());
it.remove();
}

结果: 编辑时不报错,但是执行时报错!

Exception in thread "main" java.lang.UnsupportedOperationException

原因:  Arrays.asList方法返回的ArrayList是继承自AbstractList同时实现
了RandomAccess和Serializable接口,定义如下:  

[java] view plain copy
  1. private static class ArrayList<E> extends AbstractList<E>  
  2.     implements RandomAccess, java.io.Serializable  

AbstractList这个类的定义:  

[java] view plain copy
  1. public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>   

这时我们发现AbstractList这个类的set add remove方法定义如下:

[java] view plain copy
  1. public void add(int index, E element) {  
  2.     throw new UnsupportedOperationException();  
  3. }  
  4.   
  5. public E set(int index, E element) {  
  6.     throw new UnsupportedOperationException();  
  7. }  
  8.   
  9. public E remove(int index) {  
  10.     throw new UnsupportedOperationException();  
  11. }  
解决方案:将Arrays.asList(1,2,3,4,5)放在一个新生命的List中即可

List<Integer> temp = Arrays.asList(1,2,3,4,5);
temp.set(3, 6);
List<Integer> list = new ArrayList<Integer>(temp);

这样就可以在list中进行add() 和remove()的操作;

有些同学认为是temp是只读的,但是使用set();方法对指向index的元素进行修改也是可以的。  

-------------------------------

阅读全文
0 0
原创粉丝点击