写点什么

【JAVA】List 转换为 array

用户头像
莫问
关注
发布于: 2020 年 11 月 25 日

对于引用对象

方法 1(优选)

Foo[] array = list.toArray(new Foo[0]);
复制代码

方法 2(不推荐)

Foo[] array = new Foo[list.size()];list.toArray(array); // fill the array
复制代码

说明

推荐使用方法 1,不推荐使用方法 2

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).

对于基本类型

方法


List<Integer> list = ...;int[] array = new int[list.size()];for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
复制代码

参考

https://stackoverflow.com/questions/9572795/convert-list-to-array-in-java

发布于: 2020 年 11 月 25 日阅读数: 26
用户头像

莫问

关注

站在现在看未来,站在未来看现在 2019.11.20 加入

居安思危,先忧后乐

评论

发布
暂无评论
【JAVA】List转换为array