Go How to convert an array to ArrayList in Java

Source: Internet
Author: User

Method Summary:
Element[] Array = {new Element (1), new Element (2), new Element (3)}; arraylist<element> ArrayList = new Arraylist<element> (arrays.aslist (array));  Method 1list<element> list = arrays.aslist (array);  Method 2list<element> list = new arraylist<element> (array.length); Method 3collections.addall (list, array);
Method 1, annotations

ArrayList the construction method of the document.
ArrayList (Collection <? extends E > C): Constructs a list of elements that contain a specific container, and is returned according to the order of the container iterators.
So the construction method does the following things:
1. Converting container C to an array
2. Copy the array into an array called "Elementdata" in ArrayList
The source code for the ArrayList construction method is as follows:

Public ArrayList (collection<? extends e> c) {       elementdata = C.toarray ();       size = Elementdata.length;        if (elementdata.getclass () = object[].class)             elementdata = arrays.copyof (elementdata, size, object[].class);}
Method 2, annotations

This is not the best because the size of the list returned by Aslist () is fixed. In fact, the returned list is not a java.util.ArrayList, but a private static class defined in java.util.Arrays . We know that the implementation of ArrayList is essentially an array, whereas the list returned by Aslist () is a fixed-size list supported by the original array. In this case, if you add or remove elements from the list, the program throws an exception unsupportedoperationexception.

such as: list.add( newElement(4));

Exception in thread "main"java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList at collection.ConvertArray.main(ConvertArray.java:22)。

PS: Original address: http://www.cnblogs.com/liushaobo/p/4423102.html

Go How to convert an array to ArrayList in Java

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.