解决方法

时间:2025-04-09 12:13:48

在项目中对List进行操作时报错,后来发现操作的List是由数组转换而成的,通过看源码发现问题,并写测试程序如下。
代码块:

public class ListTest {
    public static void main(String[] args) {
        String[] array = {"1","2","3","4","5"};
        List<String> list = (array);
        ("6");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

执行结果:

Exception in thread "main" 
	at (:148)
	at (:108)
	at (:11)
	at .invoke0(Native Method)
	at (:62)
	at (:43)
	at (:498)
	at (:144)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

发生问题的原因如下:
调用()产生的List中add、remove方法时报异常,这是由于()返回的是Arrays的内部类ArrayList, 而不是。Arrays的内部类ArrayList和都是继承AbstractList,remove、add等方法在AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。重写这些方法而Arrays的内部类ArrayList没有重写,所以会抛出异常。解决方法如下:

public class ListTest {
    public static void main(String[] args) {
        String[] array = {"1","2","3","4","5"};
        List<String> list = (array);
        List arrList = new ArrayList(list);
        ("6");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8