Arrays. asList () Note that Arrays. asList ()

Source: Internet
Author: User

Arrays. asList () Note that Arrays. asList ()

Api:

public static <T> List<T> asList(T... a)
Returns a list of fixed sizes supported by the specified array. (Changes to the returned list are directly written to the array .) This method is the same Collection.toArray()It serves as a bridge between array-based APIs and collection-based APIs. The returned list is serializable and implements RandomAccess.

This method also provides a convenient way to create a fixed-length list, which is initialized to contain multiple elements:

     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); 
Parameters:
a-List arrays are supported.
Return Value:
List View of the specified array.

Problems:

Java. lang. UnsupportedOperationException

Java. lang. UnsupportedOperationException occurs when you call add and remove methods after using Arrays. asList.

 

Cause:

This is because Arrays. asList () returns java. util. Arrays $ ArrayList instead of ArrayList.

Both Arrays $ ArrayList and ArrayList inherit the AbstractList, remove, add, and other methods. In AbstractList, the default throw UnsupportedOperationException is thrown and no operation is performed.

ArrayList override these methods are used to operate the list, but Arrays $ ArrayList does not have override remove (), add (), and so on, so throw UnsupportedOperationException.

 

 

Solution:

String [] arr = {"a", "B", "c "};

List <String> list = Arrays. asList (arr );

List <String> arrList = new ArrayList <String> (list );

 

 

 

 

 

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.