The Java array and list are converted to each other

Source: Internet
Author: User

1. The array is converted into a list

The array can be converted to a list using the method: Arrays.aslist, together to understand

System.out.println (Arrays.aslist (new string[] {"A", "B"});

Print: [A, b]

list<integer> asList2 = arrays.aslist (new integer[] {1, 2}); System.out.println (ASLIST2);

Printed: [1, 2]

The following results are not expected

Print: [[[Email protected]]

If you are going to convert a primitive type array to a list of the corresponding package type, use Apache Commons Lang Bar, perhaps your project is using it, similar to the following using Arrayutils.toobject:

list<integer> list = Arrays.aslist (Arrayutils.toobject (new int[] {1, 2})); SYSTEM.OUT.PRINTLN (list);

Printed: [1, 2]

Note When you use the tool class Arrays.aslist () to turn an array into a collection, you cannot use its associated method to modify the collection, and its Add/remove/clear method throws a Java.lang.UnsupportedOperationException exception. The return object of Aslist is a arrays inner class, and there is no method to implement the collection, the data in the background is still an array, and the modification of the arrays affects the collection:

string[] countries = {"China", "Russia", "American"}; list<string> AsList3 = arrays.aslist (countries); countries[2] = "France"; System.out.println (ASLIST3);

Printed: [China, Russia, France]

2.List to Group

The list toarray (t[] Array) method, passing in an array of exactly the same type, the size of the array list.size ().

list<string> fruits = new arraylist<string> () Fruits.add ("Apple"); Fruits.add ("Pear"); Fruits.add (" Orange "); string[] Array = Fruits.toarray (new String[fruits.size ()));

  

The Java array and list are converted to each other

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.