collection.toArray(new String[0])中new String[0]的作用

原文鏈接:https://blog.csdn.net/ystyaoshengting/article/details/50697783

new string[0]的作用

比如:String[] result = set.toArray(new String[0]);

 

Collection的公有方法中,toArray()是比較重要的一個。
但是使用無參數的toArray()有一個缺點,就是轉換後的數組類型是Object[]。 雖然Object數組也不是不能用,但當你真的想用一個具體類型的數組,比如String[]時,問題就來了。而把Object[]給cast成String[]還是很麻煩的,需要用到這個:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

不管是從哪方面看還是一開始就弄成String[]比較好。

具體怎麼辦呢?其實用帶參數的toArray就好了。官方是這樣給出的例子:
String[] a = c.toArray(new String[0]);

如果指定的數組能容納該 collection,則返回包含此 collection 元素的數組。否則,將根據指定數組的運行時類型和此 collection 的大小分配一個新數組。這裏給的參數的數組長度是0,因此就會返回包含此 collection 中所有元素的數組,並且返回數組的類型與指定數組的運行時類型相同。


像 toArray 方法一樣,此方法充當了基於數組的 API 與基於 collection 的 API 之間的橋樑。更進一步說,此方法允許在輸出數組的運行時類型上進行精確控制,並且在某些情況下,可以用來節省分配開銷。

假定 l 是隻包含字符串的一個已知 List。以下代碼用來將該列表轉儲到一個新分配的 String 數組: 

     String[] x = (String[]) v.toArray(new String[0]);
 注意,toArray(new Object[0]) 和 toArray() 在功能上是相同的。 

參數:
a - 存儲此 collection 元素的數組(如果其足夠大);否則,將爲此分配一個具有相同運行時類型的新數組。

 

 

Collection Interface Array Operations

 

The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. The array operations allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array.

For example, suppose that c is a Collection. The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c.

Object[] a = c.toArray();

Suppose that c is known to contain only strings (perhaps because c is of type Collection<String>). The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c.

String[] a = c.toArray(new String[0]);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章