How to convert an array into a list collection in java: 1. Use the native method and use a for() loop to split the array and add it to the List; 2. Use the Arrays.asList() method; 3 , use Collections.addAll() method; 4. Use List.of() method.
Related recommendations: "Java Video Tutorial"
Problem Description: For the given array below , how to convert into List collection?
String[] array = {"a","b","c"};
Refer to stackoverflow to summarize the following writing methods:
1. Use the native method to split the array and add it to the List
List<String> resultList = new ArrayList<>(array.length); for (String s : array) { resultList.add(s); }
2. Use Arrays.asList()
List<String> resultList= new ArrayList<>(Arrays.asList(array));
Note: When calling Arrays.asList(), its return value type is ArrayList, but this ArrayList is an internal class of Array. When calling add(), an error will be reported: java.lang.UnsupportedOperationException, and the result will be Because a certain value in the array changes, a new ArrayList needs to be constructed again.
3. Use Collections.addAll()
List<String> resultList = new ArrayList<>(array.length); Collections.addAll(resultList,array);
4. Use List.of()
This method is a new method for Java 9 and is defined in the List interface, and It is a static method, so it can be called directly from the class name.
List<String> resultList = List.of(array);
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of How to convert array to list collection in java?. For more information, please follow other related articles on the PHP Chinese website!