数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException
2018-03-26 12:14
633 查看
从别的博客上看到了出现这种情况的分析,我也不再自己从头分析了,附上大神分析好的。Java中,可以使用Arrays.asList(T... a)方法来把一个数组转换为List,返回一个受指定数组支持的固定大小的列表。此方法同 Collection.toArray()一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的,并且实现了 RandomAccess。 此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:List stooges = Arrays.asList("Larry", "Moe", "Curly");当转换后,使用add或者remove方法总是抛出java.lang.UnsupportedOperationException异常。其底层的实现代码如下:publicstatic List asList(T... a) { returnnew ArrayList(a); } 创建了一个ArrayList对象,而这个ArrayList并不是java.util包下面的ArrayList,而是java.util.Arrays类中的一个内部类,其实现代码如下:privatestaticclass ArrayList extends AbstractList implements RandomAccess, java.io.Serializable { privatestaticfinallong serialVersionUID = -2764017481108945198L;privatefinal E[] a; ArrayList(E[] array) { if (array==null) thrownew NullPointerException(); a = array; } 而这个ArrayList类又继承了AbstractList类,其中的add和remove方法的实现过程又如下:publicvoid add(int index, E element) { thrownew UnsupportedOperationException(); } public E remove(int index) { thrownew 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
- Arrays.asList()后调用add,remove这些method时出现java.lang.UnsupportedOperationException异常
- 数组转换为List后add或remove出现UnsupportedOperationException异常分析
- 数组转换为List后add或remove出现UnsupportedOperationException异常分析
- Java 数组转换成List,然后执行add或remove抛异常UnsupportedOperationException问题的解决
- Arrays.asList 转换数组后add或remove出现java.lang.UnsupportedOperationException异常
- Arrays.asList() 得到 集合 执行 add() 和 remove() 抛 UnsupportedOperationException 异常
- 数组转换为List(Arrays.asList)后add或remove出现UnsupportedOperationException异常
- Arrays.asList不能remove、add等,抛UnsupportedOperationException
- 关于 Arrays.asList add、remove 操作的 UnsupportedOperationException
- Java 数组转换成List,然后执行add或remove抛异常UnsupportedOperationException问题的解决
- 使用Arrays.asList时出现异常 java.lang.UnsupportedOperationException
- Arrays.asList() 出现java.lang.UnsupportedOperationException
- Arrays.asList的到的List进行remove操作报java.lang.UnsupportedOperationException
- Arrays.asList()引起的java.lang.UnsupportedOperationException
- Arrays.asList()使用---导致java.lang.UnsupportedOperationException分析
- List在调用add、remove方法后报java.lang.UnsupportedOperationException
- Arrays.asList() 转换为的list为什么不能进行add或者remove操作