Java uses arrays.aslist to quickly create a list collection

Source: Internet
Author: User

A case code in the program is as follows:

            New Hashmap<string, list<crontrigger>>();            Tmap.put (name, Arrays.aslist (new crontrigger[] {trigger}));

Program run throws Exception: Java.lang.UnsupportedOperationException

Cause of Error:

The Arrays.aslist method was used to quickly create a list, but the ArrayList returned by this method is not a Java.util.ArrayList object, but rather an inner class of arrays.

We can look at the source code.

Arrays.class: @SafeVarargs Public Static<T> list<t>aslist (T ... a) {return NewArraylist<>(a); }---------------------------------------------------Private Static classArraylist<e>extendsAbstractlist<e>        Implementsrandomaccess, java.io.Serializable {Private Static Final LongSerialversionuid = -2764017481108945198l; Private Finale[] A; ArrayList (e[] array) {if(array==NULL)                Throw NewNullPointerException (); A=Array; }.....

The code above shows that the inner class ArrayList inherits the Abstractlist, but does not rewrite its Add method and the Remove method, the relevant code in Abstractlist is as follows:

 Public BooleanAdd (e e) {Add (Size (), e); return true; } Public voidAddintindex, E Element) {        Throw Newunsupportedoperationexception (); } PublicE Remove (intindex) {        Throw Newunsupportedoperationexception (); }

This causes us to call the method add and remove when we use it as a Java.util.ArrayList object unsupportedoperationexception

Workaround:

1. Do not use the Arrays.aslist method, direct new Java.util.ArrayList (), and then add the object in turn (possibly with more code).

2. Still use the Arrays.aslist method, but to add the conversion, the code is as follows:

New Arraylist<crontrigger> (Arrays.aslist (new crontrigger[] {trigger}));

Java uses arrays.aslist to quickly create a list collection

Related Article

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.