[Java] 集合List轉化為數組Array的方法


Java:集合List轉化為數組Array的方法

一、使用toArray()方法

LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);

//方法一:構造與list相同容量的數組
list.toArray(new Integer[list.size()]);
//也可以這種形式
Integer[] arr = net Integer[list.size()];
list.toArray(arr);

//方法二:使用空數組
list.toArray(new Integer[0]);

更推薦使用空數組,理由如下

From JetBrains Intellij Idea inspection:

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.

This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

二、使用Java 8 Stream API

LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);

list.stream().toArray(Integer[]::new);
//自從Java 11
list.toArray(Integer[]::new);

三、使用循環

LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);

Integer[] arr = new Integer[list.size()];
for(int i = 0; i < list.size(); i ++) {
    arr[i] = list.get(i);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM