Java 如何将集合转换为数组

java.util.collection中的两种方法从集合中创建一个数组:

  • Object[] toArray()
  • T[] toArray(T[] a)

对象[] toarray()可以使用如下:

// 版本 ≥ Java SE 5
Set set = new HashSet();
set.add("red");
set.add("blue");
//although set is a Set, toArray() returns an Object[] not a String[]
Object[] objectArray = set.toArray();

T[] toArray(T[] a)可以按下面方式使用:

// 版本 ≥ Java SE 5
Set set = new HashSet();
set.add("red");
set.add("blue");
//The array does not need to be created up front with the correct size.
//Only the array type matters. (If the size is wrong, a new array will
//be created with the same type.)
String[] stringArray = set.toArray(new String[0]);
//If you supply an array of the same size as collection or bigger, it
//will be populated with collection values and returned (new array
//won't be allocated)
String[] stringArray2 = set.toArray(new String[set.size()]);

它们之间的区别不仅仅是有非类型化和类型化的结果。它们的性能也可能不同(有关详细信息,请阅读此性能分析部分):
-Object[]toArray()使用矢量化arraycopy,这比T[]toArray(T[]a)中使用的类型检查arraycopy快得多。
-T[]toArray(new T[non zero size])需要在运行时将数组归零,而T[]toArray(new T[0])则不需要。这样的动作使得调用后者比前者快。

从java se 8+开始,其中介绍了流概念,可以使用流
由集合生成,以便使用Stream.toArray方法创建新数组。

String[] strings = list.stream().toArray(String[]::new);
日期:2020-06-02 22:15:20 来源:oir作者:oir