报错信息
1
2
3
java.lang.UnsupportedOperationException: null
at java.util.AbstractList.add(AbstractList.java:148) ~[?:1.8.0_131]
at java.util.AbstractList.add(AbstractList.java:108) ~[?:1.8.0_131]
报错原因
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class test {
public static void main(String[] args) {
//定义一个字符长度为5的字符串
String[] strings = new String[5];
strings[0] = "a";
strings[1] = "b";
strings[2] = "c";
strings[3] = "d";
strings[4] = "e";
//调用Arrays中的asList方法将String[]转化为List<String>
List<String> list = Arrays.asList(strings);
System.out.println("list<String>:" + list.toString());
//为list添加一个元素
list.add("f");
System.out.println("list<String>:" + list.toString());
}
}
Arrays.asList(strings);
方法返回的List对象不是我们常见的ArrayList,而是Arrays的一个内部类,我们把返回的对象处理一下,转成我们熟悉的List实现类就可以了。
1
List<String> list = new ArrayList<>(Arrays.asList(strings));
或
1
2
List<String> list = new ArrayList<>();
list.addAll(Arrays.asList(strings));