[Java]集合List转化为数组Array的⽅法
Java:集合List转化为数组Array的⽅法
⼀、使⽤toArray()⽅法
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(2);
list.add(3);
//⽅法⼀:构造与list相同容量的数组
//也可以这种形式
Integer[] arr = net Integer[list.size()];
//⽅法⼆:使⽤空数组
更推荐使⽤空数组,理由如下
java数组字符串转数组From JetBrains Intellij Idea inspection:
There are two styles to convert a collection to an array: either using a pre-sized array (Array(new String[c.size()])) or using an empty array (Array(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 r
ecommended 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
三、使⽤循环
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] = (i);
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论