Java: Converting arrays, lists, and collections to each other

Source: Internet
Author: User

1. Array to List
string[] City = {"Nanjing", "Shanghai", "Beijing"}; List<string> citylist = arrays.aslist (city);

Note: The list size of the array conversion is fixed, the Add, remove operation cannot be performed, or the following exception is thrown:

Citylist.add ("Xiamen"); Citylist.remove (2);

If you want to control the list size, you can only add the elements in the array to the list ...

2. List Goto Array
object[] Cityarray = Citylist.toarray (); for (Object X:cityarray)     System.out.println (x);

Note: Since the list is converted to array, it is not possible to know what type of data is stored in the list, so an array is created with the object class. The results of the operation are as follows:

3. List Turn Set
string[] City = {"Nanjing", "Shanghai", "Beijing"}; List<string> citylist = arrays.aslist (city); Set listtoset = new HashSet (citylist);

  

4. Set Goto List
List List = new ArrayList (set);

  

5. Array Turn Set

Note: Convert array to list first, then set

string[] City = {"Nanjing", "Shanghai", "Beijing"}; Set set = New HashSet (arrays.aslist (city));

  

6. Set Goto Array
string[] City = {"Nanjing", "Shanghai", "Beijing"}; Set set = New HashSet (arrays.aslist (city)); object[] SetToArray = Set.toarray ();

  

Java: Converting arrays, lists, and collections 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.