Home > Java > javaTutorial > Example analysis of converting arrays and lists in Java

Example analysis of converting arrays and lists in Java

黄舟
Release: 2017-09-06 14:20:16
Original
1640 people have browsed it

This article mainly introduces the methods of converting arrays to lists and lists to arrays in Java programming. It summarizes and analyzes in detail in the form of examples the operation skills of converting arrays and lists in Java. Friends in need can refer to it. Next

The example in this article describes the method of converting an array into a list and converting a list into an array through Java programming. Share it with everyone for your reference, the details are as follows:

Convert array to list:

Method 1:


String[] userid = {"aa","bb","cc"};
List<String> userList = new ArrayList<String>();
Collections.addAll(userList, userid);
Copy after login

Method 2:


String[] userid = {"aa","bb","cc"};
List<String> userList = Arrays.asList(userid);
Copy after login

Another: Arrays.asList() returns a fixed-size list supported by the specified array. Therefore, operations such as Add and Remove cannot be performed.


List list = new ArrayList(Arrays.asList(userid));
Copy after login

That’s it.

Method 3:


String[] userid = {"aa","bb","cc"};
List<String> userList = new ArrayList<String>(userid.length);
for(String uid: userid){
userList.add(uid);
}
Copy after login

Convert list into an array:

Method 1 :


List<String> strList = new ArrayList<String>();
strList.add("aa");
strList.add("bb");
Object[] objs = strList.toArray();
Copy after login

If you want to change it into a String array, you need to force the type.


String[] strs = (String[]) strList.toArray();
Copy after login

You can also specify the size:


final int size = strList.size();
String[] strs = (String[])strList.toArray(new String[size]);
Copy after login

Method 2:


List<String> strList = new ArrayList<String>();
strList.add("aa");
strList.add("bb");
String[] strs = new String[strList.size()];
Copy after login

The above is the detailed content of Example analysis of converting arrays and lists in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template