In the normal development process, we know that an array object can be converted to a list. This way, we just have to use the Arrays.aslist method. 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.
The following is a very simple test code:
public class Mainfacade {public static void Main (string[] args) { list<integer> List = arrays.aslist ); List.add (5); System.out.print (List.tostring ()); } }
But the code above will throw out an exception like unsupportedoperationexception.
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 and implemented simultaneously
The randomaccess and serializable interfaces, defined as follows:
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 of the Abstractlist class is defined as follows:
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 that in fact, the list obtained through the Aslist method is read-only, so how can we avoid such errors in peacetime? We can use the following methods:
list<integer> list = new arraylist<> (Arrays.aslist ());
Why arrays.aslist in Java cannot use the Add and remove methods?