Tag Archives: Arrays

java.lang.UnsupportedOperationException resolvent

in the project List for operating times wrong Java. Lang. UnsupportedOperationException, later found operating List is composed of array transformation, by looking at the source code found problems, and write the test procedure is as follows.
code block:

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

execution result:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
	at com.atguigu.test.ListTest.main(ListTest.java:11)
	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:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

The problem with

is the following: the add and remove methods in the List generated by the
call on arrays.aslist () are exception because ArrayList of the inner class of arrays.aslist () is returned instead of java.util.ArrayList. Arrays of inner class ArrayList and Java. Util. ArrayList are inherited AbstractList, remove, add method is the default in AbstractList throw UnsupportedOperationException and don’t make any operation. Java.util.ArrayList overrides these methods, but the ArrayList of Arrays internal class does not, so it will throw an exception. The solution:

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