1.List轉換成為數組。(這里的List是實體是ArrayList)
調用ArrayList的toArray方法。
toArray
public T[] toArray(T[]
a)返回一個按照正確的順序包含此列表中所有元素的數組;返回數組的運行時類型就是指定數組的運行時類型。如果列表能放入指定的數組,則返回放入此列表元
素的數組。否則,將根據指定數組的運行時類型和此列表的大小分配一個新的數組。
如果指定的數組能容納列表并有剩余空間(即數組的元素比列表的多),那么會將數組中緊跟在集合末尾的元素設置為 null。這對確定列表的長度很有用,但只 在調用方知道列表中不包含任何 null 元素時才有用。
指定者:
接口 Collection 中的 toArray
指定者:
接口 List 中的 toArray
覆蓋:
類 AbstractCollection 中的 toArray
參數:
a - 要存儲列表元素的數組,如果它足夠大的話;否則,它是一個為存儲列表元素而分配的、具有相同運行時類型的新數組。
返回:
包含列表元素的數組。
拋出:
ArrayStoreException - 如果 a 的運行時類型不是此列表中每個元素的運行時類型的超類型。
具體用法:
List list = new ArrayList();
list.add("1");
list.add("2");
final int size = list.size();
String[] arr = (String[])list.toArray(new String[size]);
2.數組轉換成為List。
調用Arrays的asList方法.
asList
public static List asList(T...
a)返回一個受指定數組支持的固定大小的列表。(對返回列表的更改會“直寫”到數組。)此方法同 Collection.toArray
一起,充當了基于數組的 API 與基于 collection 的 API 之間的橋梁。返回的列表是可序列化的,并且實現了
RandomAccess。
此方法還提供了一個創建固定長度的列表的便捷方法,該列表被初始化為包含多個元素:
List stooges = Arrays.asList("Larry", "Moe", "Curly");
參數:
a - 支持列表的數組。
返回:
指定數組的列表視圖。
另請參見:
Collection.toArray()
具體用法:
String[] arr = new String[] {"1", "2"};
List list = Arrays.asList(arr);
-------------------------------------------------------------------------------------------------------------------------------
Arrays.asList is a feature every Java developer should know about. It'll save you from writing code like:
List<Foo> foolist = new ArrayList<Foo>();
foolist.add(foo);
return foolist;
or maybe
if(map.containsKey(id)){
map.get(id).add(foo);
}else{
List<Foo> foolist = new ArrayList<Foo>();
foolist.add(foo);
map.put(id, foo);
}
and allow you to write code like:
return Arrays.asList(foo);
and
if(map.containsKey(id))
map.get(id).add(foo);
else
map.put(id, Arrays.asList(foo));
Update: I didn't notice that Arrays.asList returns a List
that can't be added too. When you try to call add on the returned List,
you'll get an UnsupportedOperationException in AbstractList.add. That
seemed lame to me, but the List interface does say that add is an
"optional operation". For the lists to be mutable, the above code
snippets have to be changed to something like:
return new ArrayList<Foo>(Arrays.asList(foo));
and
if(map.containsKey(id))
map.get(id).add(foo);
else
map.put(id, new ArrayList<Foo>(Arrays.asList(foo)));
Update: Of course, the more pathalogical example of what Arrays.asList saves you from is:
List<Foo> foolist = new ArrayList<Foo>(fooarray.length);
for(int i=0,n=fooarray.length; i<n; i++){
foolist.add(fooarray[i]);
}
or
List<Foo> foolist = new ArrayList<Foo>(fooarray.length);
for(Foo f : fooarray){
foolist.add(f);
}
because that becomes just:
List<Foo> foolist = Arrays.asList(fooarray);