Java數組是一種容器類型,能夠存儲一個固定大小的同類型元素集合。而List是Java Collection Framework中的一個介面,能夠動態地添加或刪除元素。在開發中,我們經常需要將一個數組轉化為List來方便使用。本文將從多個方面介紹Java中數組轉化為List的方法。
一、使用Arrays.asList()
Arrays.asList()是Java中將數組轉化為List的最便捷方式。它接受一個數組作為參數,並返回一個List對象。這個List對象是固定的,長度和數組一樣。由於它返回一個List對象,因此可以使用List的任何函數和方法進行訪問、操作。下面是一個示例:
public class ArrayToListExample {
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
List < Integer > intList = Arrays.asList(intArray);
System.out.println(intList);
}
}
輸出結果為:[1, 2, 3, 4, 5]。
需要注意的是,如果使用基本數據類型的數組,如int[],會將整個數組作為一個元素加入List中,而不是將數組中的元素逐個添加到List中。
二、使用Collections.addAll()
另一種將數組轉化為List的方法是使用Collections.addAll()。該方法接受一個List和一個數組作為參數。它將數組中的元素逐個添加到List中。下面是一個示例:
public class ArrayToListExample {
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
List < Integer > intList = new ArrayList < > ();
Collections.addAll(intList, Arrays.stream(intArray)
.boxed()
.toArray(Integer[]::new));
System.out.println(intList);
}
}
輸出結果為:[1, 2, 3, 4, 5]。
需要注意的是,這種方法會創建一個新的List對象,並將數組中的元素逐個添加到List中。因此,如果數組中有大量元素,可能會導致性能問題。
三、使用循環逐個添加
第三種將數組轉化為List的方法是使用循環逐個添加。該方法比較麻煩,但是可以讓你更加自由地控制每個元素的添加方式。下面是一個示例:
public class ArrayToListExample {
public static void main(String[] args) {
int[] intArray = {1, 2, 3, 4, 5};
List < Integer > intList = new ArrayList < > ();
for (int i = 0; i < intArray.length; i++) {
intList.add(intArray[i]);
}
System.out.println(intList);
}
}
輸出結果為:[1, 2, 3, 4, 5]。
需要注意的是,由於每次循環都會調用add()方法,因此這種方法可能會導致性能問題,特別是當數組中有大量元素的時候。
四、將List轉換為數組
Java中也支持將List轉換為數組的操作。下面是一個示例:
public class ListToArrayExample {
public static void main(String[] args) {
List < Integer > intList = new ArrayList < > ();
intList.add(1);
intList.add(2);
intList.add(3);
int[] intArray = intList.stream()
.mapToInt(Integer::intValue)
.toArray();
System.out.println(intArray);
}
}
輸出結果為:[I@70dea4e。
需要使用Arrays.toString(intArray)將其轉換為字元串輸出。
五、將List轉換為Array的其中一種方法
先給大家介紹一個很實用的工具類:org.apache.commons.lang3.ArrayUtils,它可以方便地處理數組。下面是一個示例:
public class ListToArrayExample {
public static void main(String[] args) {
List < Integer > intList = new ArrayList < > ();
intList.add(1);
intList.add(2);
intList.add(3);
int[] intArray = ArrayUtils.toPrimitive(intList.toArray(new Integer[intList.size()]));
System.out.println(intArray);
}
}
輸出結果為:[1, 2, 3]。
需要注意的是,該方法調用時需要添加org.apache.commons.lang3.ArrayUtils包。如果沒有該包,請在pom.xml文件中添加以下依賴:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
以上就是Java中數組轉化為List的幾種方式。根據不同的需求,可以選擇不同的方法。當然,上述方法並不是全部的方法,還有其他方式,例如使用Java 8 Stream API等。
原創文章,作者:DKEO,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/133699.html