Operation of the list in the project times wrong java.lang.UnsupportedOperationException, and later found that the list of operations by the conversion of the array, by looking at the source code to find the problem, and write the test program as follows.
Code block:
Public class listtest { publicstaticvoid main (string[] args) { = {"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 108 11 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 occurs for the following reasons:
Call Arrays.aslist () the Add, remove method times exception for the list produced by Arrays.aslist (), which is the inner class arraylist of the city arrays returned by the Rather than java.util.ArrayList. Arrays's inner class ArrayList and Java.util.ArrayList are inherited Abstractlist,remove, add, and so on are the default throw in Abstractlist Unsupportedoperationexception and does not do anything. Java.util.ArrayList re-arrays these methods and the inner class ArrayList is not re-thrown, it throws an exception. The workaround is as follows:
Public class listtest { publicstaticvoid main (string[] args) { = {"1", "2", " 3 "," 4 "," 5 "}; List<String> list = arrays.aslist (array); New ArrayList (list); Arrlist.add ("6");} }
Java.lang.UnsupportedOperationException solution caused by arrays.aslist