Home  >  Article  >  Java  >  How to convert array to List in Java?

How to convert array to List in Java?

WBOY
WBOYforward
2023-04-26 21:04:068989browse

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

2. Use Arrays.asList()

ListresultList=newArrayList<>(Arrays.asList);

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

4. Use List.of()

List resultList = List.of(array);

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete