During the usual development process, we know that we can convert an array object to a list. This kind of operation, we only have to use arrays.aslist this method can be. I have been using this method for a while, and one day I found that the list I got through Arrays.aslist was unable to do the add and remove operations.
Here is a very easy test code:
public class Mainfacade {public static void Main (string[] args) { list<integer> List = arrays.aslist ); List.add (5); System.out.print (List.tostring ()); } }
Just the code above will throw out a unsupportedoperationexception this exception
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.popkit.MainFacade.main (mainfacade.java:14) at SUN.REFLECT.NATIVEMETHODACCESSORIMPL.INVOKE0 (Native Method) at Sun.reflect.NativeMethodAccessorImpl.invoke ( nativemethodaccessorimpl.java:57) at Sun.reflect.DelegatingMethodAccessorImpl.invoke ( delegatingmethodaccessorimpl.java:43) at Java.lang.reflect.Method.invoke (method.java:606) at Com.intellij.rt.execution.application.AppMain.main (appmain.java:134)
The reason is that the ArrayList returned by the Arrays.aslist method is inherited from Abstractlist at the same time
The randomaccess and serializable interfaces. Definitions such as the following:
private static class Arraylist<e> extends Abstractlist<e> implements Randomaccess, Java.io.Serializable
Let's take a look at the definition of the Abstractlist class:
At this point we find that the Set Add Remove method definition for this class abstractlist such as the following:
public void Add (int index, E element) { throw new unsupportedoperationexception (); } Public E Set (int index, E element) { throw new unsupportedoperationexception (); } Public E Remove (int index) { throw new unsupportedoperationexception (); }
Now I know the reason why it throw unsupportedoperationexception exception.
Through the above analysis, we know. In fact, the list obtained by the Aslist method is read-only. So how do we avoid this error at ordinary times? We can use the following methods, for example:
list<integer> list = new arraylist<> (Arrays.aslist ());
Why arrays.aslist in Java cannot use the Add and remove methods?