Java.lang.UnsupportedOperationException solution caused by arrays.aslist

Source: Internet
Author: User

Operation of the list in the project times wrong java.lang.UnsupportedOperationException, and later found that the list of operations by the conversion of the array, by looking at the source code to find the problem, and write the test program as follows.
Code block:

 Public class listtest {    publicstaticvoid  main (string[] args) {        = {"1", "2", " 3 "," 4 "," 5 "};        List<String> list = arrays.aslist (array);        List.add ("6");}    }

Execution Result:

 Exception in thread ' main '  java.lang.UnsupportedOperationException at Java.util.AbstractList.add (Abstractlist.java:  148 108 11 62) at Sun.reflect.DelegatingMethodAccessorImpl.invoke (Delegatingmethodaccessorimpl.java:  43 ) at Java.lang.reflect.Method.invoke (Method.java:  498 ) at Com.intellij.rt.execution.application.AppMain.main (Appmain.java:  144) 

The problem occurs for the following reasons:  
Call Arrays.aslist () the Add, remove method times exception for the list produced by Arrays.aslist (), which is the inner class arraylist of the city arrays returned by the Rather than java.util.ArrayList. Arrays's inner class ArrayList and Java.util.ArrayList are inherited Abstractlist,remove, add, and so on are the default throw in Abstractlist Unsupportedoperationexception and does not do anything. Java.util.ArrayList re-arrays these methods and the inner class ArrayList is not re-thrown, it throws an exception. The workaround is as follows:

 Public class listtest {    publicstaticvoid  main (string[] args) {        = {"1", "2", " 3 "," 4 "," 5 "};        List<String> list = arrays.aslist (array);         New ArrayList (list);        Arrlist.add ("6");}    }

Java.lang.UnsupportedOperationException solution caused by arrays.aslist

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.