1.List轉(zhuǎn)換成為數(shù)組。(這里的List是實(shí)體是ArrayList)
調(diào)用ArrayList的toArray方法。
toArray
public T[] toArray(T[]
a)返回一個(gè)按照正確的順序包含此列表中所有元素的數(shù)組;返回?cái)?shù)組的運(yùn)行時(shí)類型就是指定數(shù)組的運(yùn)行時(shí)類型。如果列表能放入指定的數(shù)組,則返回放入此列表元
素的數(shù)組。否則,將根據(jù)指定數(shù)組的運(yùn)行時(shí)類型和此列表的大小分配一個(gè)新的數(shù)組。
如果指定的數(shù)組能容納列表并有剩余空間(即數(shù)組的元素比列表的多),那么會(huì)將數(shù)組中緊跟在集合末尾的元素設(shè)置為 null。這對(duì)確定列表的長(zhǎng)度很有用,但只 在調(diào)用方知道列表中不包含任何 null 元素時(shí)才有用。
指定者:
接口 Collection 中的 toArray
指定者:
接口 List 中的 toArray
覆蓋:
類 AbstractCollection 中的 toArray
參數(shù):
a - 要存儲(chǔ)列表元素的數(shù)組,如果它足夠大的話;否則,它是一個(gè)為存儲(chǔ)列表元素而分配的、具有相同運(yùn)行時(shí)類型的新數(shù)組。
返回:
包含列表元素的數(shù)組。
拋出:
ArrayStoreException - 如果 a 的運(yùn)行時(shí)類型不是此列表中每個(gè)元素的運(yùn)行時(shí)類型的超類型。
具體用法:
List list = new ArrayList();
list.add("1");
list.add("2");
final int size = list.size();
String[] arr = (String[])list.toArray(new String[size]);
2.數(shù)組轉(zhuǎn)換成為L(zhǎng)ist。
調(diào)用Arrays的asList方法.
asList
public static List asList(T...
a)返回一個(gè)受指定數(shù)組支持的固定大小的列表。(對(duì)返回列表的更改會(huì)“直寫”到數(shù)組。)此方法同 Collection.toArray
一起,充當(dāng)了基于數(shù)組的 API 與基于 collection 的 API 之間的橋梁。返回的列表是可序列化的,并且實(shí)現(xiàn)了
RandomAccess。
此方法還提供了一個(gè)創(chuàng)建固定長(zhǎng)度的列表的便捷方法,該列表被初始化為包含多個(gè)元素:
List stooges = Arrays.asList("Larry", "Moe", "Curly");
參數(shù):
a - 支持列表的數(shù)組。
返回:
指定數(shù)組的列表視圖。
另請(qǐng)參見(jiàn):
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);