2007年5月30日 星期三

Java API 將陣列轉為List

有些時候會有需要將Array轉換為Collection使用。
大部分的做法會自行寫一個迴圈將陣列中的物件,一一搬到Collection中。
但比較好的做法是,使用Java API
--------------------------------------------------------------------------------

java.util
Class Arrays
java.lang.Object
+--java.util.Arrays


--------------------------------------------------------------------------------

asList
public static <T> List<T> asList(T... a)
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray. The returned list is serializable and implements RandomAccess.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:

List stooges = Arrays.asList("Larry", "Moe", "Curly");
另一個方式為
List stooges = Arrays.asList(String[]{"Larry", "Moe", "Curly"});

Parameters:
a - the array by which the list will be backed.
Returns:
a list view of the specified array.
See Also:
Collection.toArray()

沒有留言: