Java.Util.Arrays can convert an array to a list, specifically defined as follows:
@SafeVarargspublic static <T> list<t> aslist (T ... a) { return new arraylist<> (a);}
You can see that the array is actually converted into a arraylist<> it seems to be no problem, but when we use Add and remove, we will find that it throws Unsupportedoperationexception, why? This is unscientific!
Enter arrays source code only to discover ... This deceptive ...
1. List<> is returned in the Arrays.aslist method, but in fact it inherits Abstractlist<> |
2. Abstractlist<> inherited from Abstractcollection<> and list<> |
3. Arrays.aslist after the list<> is unable to operate the add and remove, will throw Unsupportedoperationexception exception |
The arraylist<> definition returned in Arrays.aslist:
private static class Arraylist<e> extends Abstractlist<e> implements Randomaccess, java.io.serializable{... }
Definition of Abstractlist:
Public abstract class Abstractlist<e> extends abstractcollection<e> implements list<e> { ...}
Then look at the implementation of the Add and remove methods in the arraylist<e>, search for a bit, did not find the add and remove methods!
Okay, I'll go to abstractlist, search, find the definition of the Add method:
Public boolean Add (E e) { Add (size (), e); return true;}
All right, that goes on. F3 find the definition of Add (int index, E Element):
public void Add (int index, E element) { throw new unsupportedoperationexception ();}
What did you see? Hang on, Dad!
And look at the Remove method:
Public E Remove (int index) { throw new unsupportedoperationexception ();}
OK, a row of black lines ah ...
Finally found the reason, then how to deal with it?
Solution:
Need to be treated with ArrayList:
Long[] Idlongarrs = {1L, 2L, 3L}; arraylist<long> ids = new Arraylist<long> (arrays.aslist (Idlongarrs));
Java's arrays.aslist Trap