Java中关于数组转换成List的注意事项
Contents
问题代码
package org.emacsist;
import java.util.Arrays;
import java.util.List;
/**
* Created by sky on 16-2-14.
*/
public class TestHello {
public static void main(String[] args) {
List<String> arg = Arrays.asList(args);
arg.add("出现问题了.");
System.out.println(arg);
}
}
一运行,就报如下错误
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at org.emacsist.TestHello.main(TestHello.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Process finished with exit code 1
原因
Arrays.asList(args);
这个方法,根据JavaDoc
它返回的是一个固定大小的List,这意味着不支持任何修改的操作。比如add, remove等.
返回一个可修改的List
package org.emacsist;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by sky on 16-2-14.
*/
public class TestHello {
public static void main(String[] args) {
List<String> arg = new ArrayList<>(Arrays.asList(args));
arg.add("不会出现问题了.");
System.out.println(arg);
}
}
执行的结果如下:
[不会出现问题了.]
Process finished with exit code 0