读书人

Java List与数组其间的转换

发布时间: 2013-01-01 14:04:18 作者: rapoo

Java List与数组之间的转换

1 数组转换为List

调用Arrays类的静态方法asList。

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<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); 

Parameters:a - the array by which the list will be backedReturns:a list view of the specified array

API中提供了一种使用的方法。更为常用的示例代码:

List<String> list = new ArrayList<String>();list.add("str1");list.add("str2");int size = list.size();String[] arr = (String[])list.toArray(new String[size]);//使用了第二种接口,返回值和参数均为结果

读书人网 >编程

热点推荐