Java's arrays.aslist Trap

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.