Arrays. aslist usage and exceptions

Source: Internet
Author: User

Convert an array into a list. We usually get used to writing it like this: List <string> List = arrays. aslist ("1", "2 ");

So we get a list, but the implementation class of this list is Java. util. arrays. arraylist (instead of Java. util. arraylist ).

By analyzing the JDK source code, we can find that Java. util. arrays. arraylist (which is converted to list) inherits the java. util. abstractlist class.

Let's take a look at what the java. util. abstractlist class looks like? We can find that

Public e set (INT index, e element)

Public e set (INT index, e element)

Public E remove (INT index)

Public void add (INT index, e element) | public Boolean add (e) call add (INT index, e element)

All of the above methods throw an unsupportedoperationexception.

Therefore, the list converted from arrays. aslist is actually a javasactlist, which can be accessed like a list, but cannot be modified.

This also explains why the add and remove operations on the list output from arrays. aslist throw the unsupportedoperationexception. From the JDK code perspective, this is the cause.

In other words, Java. util. arrays. arraylist is actually just a decoration of the array. We can see the implementation in it. e get (INT index), e set (INT index, e element) and other methods are all Array Operations, his goal is to provide the ability to access arrays just like the access list. In essence, it is still an array.

 

Arrays. aslist usage and exceptions

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.