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

來源:互聯網
上載者:User

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]);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.