如果我们将一个数组作为参数传递给方法toArray
,那么它会使用 list 的项目填充它,否则它会返回一个Object
. 我们可以传递一个比列表更大的数组作为参数来获得一个更大的数组。下面的例子解释了它:
public static void main(String[] args) throws FileNotFoundException {
List<String> list = new ArrayList<>();
list.add("One");
System.out.println("list Size: " + list.size());
//If we pass an array as argument it will be filled with items from list and then returned. Here array size is (list.size +2 )
String[] stringArray = list.toArray(new String[2]);
System.out.println("stringArray Size: " + stringArray.length);
//If we do not pass an array as argument we get Object[] of same size
Object[] objects = list.toArray();
System.out.println("objects Size: " + objects.length);
// Java 8 has option of streams to get same size array
String[] stringArrayUsingStream = list.stream().toArray(String[]::new);
System.out.println("stringArrayUsingStream Size: " + stringArrayUsingStream.length);
}
如上所示,我们在 Java 8 中也可以选择使用流。输出为:
list Size: 1
stringArray Size: 2
objects Size: 1
stringArrayUsingStream Size: 1