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

Example analysis of converting arrays and lists in Java

黄舟
黄舟Original
2017-09-06 14:20:161635browse

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);

Method 2:


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

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));

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);
}

Convert list into an array:

Method 1 :


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

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


String[] strs = (String[]) strList.toArray();

You can also specify the size:


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

Method 2:


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

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!

Statement:
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