1. 程式人生 > >【java基礎】collection介面中toArray()的使用方法

【java基礎】collection介面中toArray()的使用方法

Collection介面中有兩種toArray()方法

Object[] toArray()           Return an Array Containing all of the elements in this collection.

<T> T[] toArray(T[] a)     Return an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

 兩種方法從集合轉換成陣列,但是實現上有不同

第一種用法:

一個ArrayList<String>轉換成String型陣列

Collection<String> coll = new ArrayList<String>();

String[]  str= coll.toArray();

第二種用法:

同樣,一個ArrayList<String>轉換成String型陣列,與上不同的是,這要先申請好陣列大小

Collection<String> coll = new ArrayList<String>();

String[] theStrings = new String[ coll.size() ];

Coll.toArray(theStrings );