Home > Java > javaTutorial > body text

How to convert array to List in Java?

WBOY
Release: 2023-04-26 21:04:06
forward
8992 people have browsed it

1. Use native mode, split the array, and add it to List

List resultList = new ArrayList<>(array.length);
for (String s : array) {
resultList.add(s);
}
Copy after login

2. Use Arrays.asList()

ListresultList=newArrayList<>(Arrays.asList);
Copy after login

Note: When Arrays.asList() is called, its return value type is ArrayList, but this ArrayList is an internal category of Array. When add() is called, it will report an error: java.lang.UnsupportedOperationException, the result will change due to a certain value in the array, so a new ArrayList needs to be rebuilt.

3. Use Collections.addAll()

private void testArrayCastToListEfficient(){
  String[] strArray = new String[2];
  ArrayList< String> arrayList = new ArrayList<String>(strArray.length);
  Collections.addAll(arrayList, strArray);
  arrayList.add("1");
  System.out.println(arrayList);
 }
Copy after login

4. Use List.of()

List resultList = List.of(array);
Copy after login

This method is a new method in Java 9. It is defined in the List interface. It is a static method and can directly call the class name.

The above is the detailed content of How to convert array to List in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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