Java improvements () ----- java Set details (2): asList defects, ----- javaaslist

Source: Internet
Author: User

Java improvements () ----- java Set details (2): asList defects, ----- javaaslist

In the actual development process, we often use asList to convert arrays to lists. This method is very convenient to use, but the asList method has several defects:

1. Avoid converting the basic data type array to a list

When you convert an array of eight basic types to a list, there will be a taste defect. First look at the following program:

public static void main(String[] args) {        int[] ints = {1,2,3,4,5};        List list = Arrays.asList(ints);        System.out.println("list'size:" + list.size());    }    ------------------------------------    outPut:    list'size:1

The running result of the program is not 5 as we expected, but 1 against the day. What is the situation? First look at the source code:

public static <T> List<T> asList(T... a) {        return new ArrayList<>(a);    }

The parameter accepted by asList is a generic variable-length parameter. We know that the basic data type cannot be hairstyle, that is, eight basic types cannot be used as asList parameters, to use a generic parameter, you must use the corresponding packaging type. But why is there no error in this instance? This instance regards an array of the int type as its parameter, while an array in Java is an object, which can be generic. Therefore, this example will not produce errors. In this example, the entire int type array is used as a generic parameter, so after asList conversion, there is only one int list. As follows:

Public static void main (String [] args) {int [] ints = {1, 2, 4, 5}; List list = Arrays. asList (ints); System. out. println ("list type:" + list. get (0 ). getClass (); System. out. println ("list. get (0) = ints: "+ list. get (0 ). equals (ints);} -------------------------------------------- outPut: list type: class [Ilist. get (0) = ints: true

From this running result, we can fully prove that the element in the list is an int array. After this is done, the modification method is clear: Change int to Integer.

Public static void main (String [] args) {Integer [] ints = {1, 2, 4, 5}; List list = Arrays. asList (ints); System. out. println ("list 'size:" + list. size (); System. out. println ("list. type of get (0): "+ list. get (0 ). getClass (); System. out. println ("list. get (0) = ints [0]: "+ list. get (0 ). equals (ints [0]);} ------------------------------------------ outPut: list 'size: 5 list. type of get (0): class java. lang. integer list. get (0) = ints [0]: true

>>>>>> Java details (2.1): Do not use the basic data type as a parameter when using asList.

Ii. list generated by asList cannot be operated

Make a small modification to the above instance:

public static void main(String[] args) {        Integer[] ints = {1,2,3,4,5};        List list = Arrays.asList(ints);        list.add(6);    }

This example illustrates how to convert ints to the list category through asList, and then add an element through the add method. This instance is simple and cannot be simple, but what about the running result? As expected:

Exception in thread "main" java.lang.UnsupportedOperationException    at java.util.AbstractList.add(Unknown Source)    at java.util.AbstractList.add(Unknown Source)    at com.chenssy.test.arrayList.AsListTest.main(AsListTest.java:10)

An UnsupportedOperationException is thrown in the running result. This exception indicates that the add method is not supported in the list. This makes us depressed. How can the list method not support the add method? Is jdk head congested? Let's look at the source code of asList:

public static <T> List<T> asList(T... a) {        return new ArrayList<>(a);    }

After the asList accepts the parameter, a new ArrayList is directly added. It seems that there is no error here? Don't worry. Let's look at it again:

private static class ArrayList<E> extends AbstractList<E>    implements RandomAccess, java.io.Serializable{        private static final long serialVersionUID = -2764017481108945198L;        private final E[] a;        ArrayList(E[] array) {            if (array==null)                throw new NullPointerException();            a = array;        }        //.................    }

This is the source code of ArrayList. From this we can see that this ArrayList is not java. util. ArrayList, It is the internal class of Arrays. This internal class provides the size, toArray, get, set, indexOf, and contains methods, while methods such as add and remove that change the list result are inherited from the AbstractList parent class, at the same time, these methods are also amazing. It directly throws the UnsupportedOperationException exception:

public boolean add(E e) {        add(size(), e);        return true;    }        public E set(int index, E element) {        throw new UnsupportedOperationException();    }        public void add(int index, E element) {        throw new UnsupportedOperationException();    }        public E remove(int index) {        throw new UnsupportedOperationException();    }

Through the code, we can see that the list returned by asList is just a list, and it does not have the basic features (extended) of list ). This list is an unchangeable list. The returned list can only be long if the array of input parameters is long. Therefore:

>>>>> Java details (2.2): do not try to change the list returned by the asList. Otherwise, you will suffer from bitter fruit.


How to Use the ArrayasList () function [JAVA]

Speechless

Why compile on my machine. Can't even get the first reference?
C: \ shiyan123.java: 19: incompatible type

Find: java. util. List <Power>
Required: java. util. List <Snow>

It seems that this reference cannot be made at all.

I tried 2nd times and it seems like this:
List sonw1 = Arrays. asList (new Power ());
Sonw1.add (Arrays. asList (new light ()));
That is to say, when 1 starts to declare a list, the type is not declared at all. ''' Direct List xxx = xxx;

This is acceptable, but an exception occurs. · UnsupportedOperationException.
Speechless.

Based on my previous experience, I tried again, and the reason must be on Arrays. asList.
I tried it just now. You can do this: List <Snow> sonw1 = new ArrayList <Snow> ();
Sonw1.add (new Power ());
Sonw1.add (new light ());
That is to say, the container class supports upward transformation.
List <snow> snow1 = Arrays. asList (); the problem lies in this sentence.
If asList is written like this in the API, a fixed-size list supported by the specified array is returned.
Returns a fixed-size list of the specified array, that is, the following prompt during previous compilation:
Find: java. util. List <Power>
Required: java. util. List <Snow>
That is to say, it may have previously been: assign a List <Power> class container object to a List <Sonw> reference (that is, probably equivalent to this ): list <Snow> xx = new ArrayList <Power> (); in this case, an upward transformation cannot take place. Therefore, the matching is incorrect.
When you first create a List <Snow> sonw1 = new ArrayList <Snow> (); then, a List <Snow> class container object is created, and assigned a reference to the List <Snow> class.
Then, add a subclass of the Snow class. Sonw1.add (new light (); it seems to be a matter of course.

In fact, as I tried later, List <Snow> sonw1 = new ArrayList <Power> (); in this way, compilation is impossible. Your previous List <Snow> snow1 = Arrays. asList (new Power) should basically be the same as the List <Snow> sonw1 = new ArrayList <Power> ();
When creating a container for one pair of objects: List <xxx> snow1 = new ArrayList <xxx>, the XXX in the brackets on both sides should be the same class. Otherwise, the type does not match .... Remaining full text>

What is the list type object returned by java aslist (obj?

You cannot use new to instantiate an object. The ArrayList interface also has an implementation class. ArrayList implements the List interface. You can use new ArrayList () to obtain an instance and ArrayList implements the List, of course, its instance also has the List feature. The asList (obj) method returns a List-type instance.

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.