java.lang.UnsupportedOperationException

来源:互联网 发布:坚果s1安装软件 编辑:程序博客网 时间:2024/05/16 07:30

java.lang.UnsupportedOperationException

Javathread

 

  在使用Arrays.asList()后调用add,remove这些method时出现java.lang.UnsupportedOperationException异常。这是由于Arrays.asList() 返回java.util.Arrays$ArrayList, 而不是ArrayList。Arrays$ArrayList和ArrayList都是继承AbstractList,remove,add等method在AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。ArrayList override这些method来对list进行操作,但是Arrays$ArrayList没有override remove(),add()等,所以throw UnsupportedOperationException。

      例子:

Java代码  收藏代码
  1. package com.test;  
  2.   
  3. import java.util.Arrays;  
  4. import java.util.List;  
  5.   
  6. public class TestUnsupported {  
  7.   public static void main(String[] args) {  
  8.         String[] s = {  
  9.             "one""two""three""four""five",  
  10.             "six""seven""eight""nine""ten",  
  11.           };  
  12.   
  13.         List a = Arrays.asList(s);  
  14.         System.out.println(  
  15.           "a.contains(" + s[0] + ") = " +  
  16.           a.contains(s[0]));  
  17.         a.add("eleven"); // Unsupported  
  18.         a.remove(s[0]); // Unsupported  
  19.       }  
  20. }  
 

运行后,抛出异常如下:

Java代码  收藏代码
  1. Exception in thread "main" java.lang.UnsupportedOperationException  
  2.  at java.util.AbstractList.add(AbstractList.java:151)  
  3.  at java.util.AbstractList.add(AbstractList.java:89)  
  4.  at com.test.TestUnsupported.main(TestUnsupported.java:28)  
 

解决方法是使用Iterator,或者转换为ArrayList

Java代码  收藏代码
  1. List arrayList = new ArrayList(a);  

参考

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

 

转:http://lzrzhao.iteye.com/blog/466860