数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
来源:互联网 发布:正规网络博客 编辑:程序博客网 时间:2024/05/23 00:41
从别的博客上看到了出现这种情况的分析,我也不再自己从头分析了,附上大神分析好的。
Java中,可以使用Arrays.asList(T... a)方法来把一个数组转换为List,返回一个受指定数组支持的固定大小的列表。此方法同 Collection.toArray()一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的,并且实现了 RandomAccess。
此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
当转换后,使用add或者remove方法总是抛出java.lang.UnsupportedOperationException异常。
其底层的实现代码如下:
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
创建了一个ArrayList对象,而这个ArrayList并不是java.util包下面的ArrayList,而是java.util.Arrays类中的一个内部类,其实现代码如下:
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
而这个ArrayList类又继承了AbstractList类,其中的add和remove方法的实现过程又如下:
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
所以,肯定为出现不支持操作的异常。
那么,一种解决办法是把列表再拷贝到ArrayList中就好了。
ArrayList newList = new ArrayList<>(list);就可以使用add()和remove()方法了。
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
- 数组转换为List后add或remove出现UnsupportedOperationException异常分析
- 数组转换为List后add或remove出现UnsupportedOperationException异常分析
- Arrays.asList(strArray)转换为List,执行remove(),报异常:java.lang.UnsupportedOperationException深究
- 关于 Arrays.asList add、remove 操作的 UnsupportedOperationException
- Arrays.asList不能remove、add等,抛UnsupportedOperationException
- Java 数组转换成List,然后执行add或remove抛异常UnsupportedOperationException问题的解决
- Java 数组转换成List,然后执行add或remove抛异常UnsupportedOperationException问题的解决
- Java数组转换List后使用用add,remove抛UnsupportedOperationException异常
- Arrays.asList转换数组为集合List对象
- Arrays.asList() 返回的list不能add,remove
- Arrays.asList() 返回的list不能add,remove
- Arrays.asList()返回的List不能add和remove
- 解决Arrays.asList不能用add或remove
- Arrays.asList() 得到 集合 执行 add() 和 remove() 抛 UnsupportedOperationException 异常
- Arrays.asList() 出现java.lang.UnsupportedOperationException
- iOS 利用正则表达式 验证电话号码
- IReport PDF 中文不显示问题
- chrome下获取元素实际margin的方法
- MySQL数据库优化心得
- cocos2d android 游戏开发学习——CCAction(一)
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
- Python基础学习篇—类(Class)
- 2014.12.30随笔
- 用户枚举来实现单例模式
- 数据库优化原则
- opengl和glut
- 12月30日 面向对象04------类的练习、包
- MVC中页面传值方式总结
- 147 柳仁淑 靜叟