java list,set,map,數(shù)組間的相互轉(zhuǎn)換詳解
1.list轉(zhuǎn)set
1
|
Set set = new HashSet( new ArrayList()); |
2.set轉(zhuǎn)list
1
|
List list = new ArrayList( new HashSet()); |
3.數(shù)組轉(zhuǎn)為list
1
|
List stooges = Arrays.asList( "Larry" , "Moe" , "Curly" ); |
此時stooges中有有三個元素。注意:此時的list不能進行add操作,否則會報 “java.lang.UnsupportedOperationException”,Arrays.asList()返回的是List,而且是一個定 長的List,所以不能轉(zhuǎn)換為ArrayList,只能轉(zhuǎn)換為AbstractList
原因在于asList()方法返回的是某個數(shù)組的列表形式,返回的列表只是數(shù)組的另一個視圖,而數(shù)組本身并沒有消失,對列表的任何操作最終都反映在數(shù)組上. 所以不支持remove,add方法的
1
2
|
String[] arr = { "1" , "2" }; List list = Arrays.asList(arr); |
4.數(shù)組轉(zhuǎn)為set
1
2
|
int [] a = { 1 , 2 , 3 }; Set set = new HashSet(Arrays.asList(a)); |
5.map的相關(guān)操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
Map map = new HashMap(); map.put( "1" , "a" ); map.put( '2' , 'b' ); map.put( '3' , 'c' ); System.out.println(map); // 輸出所有的值 System.out.println(map.keySet()); // 輸出所有的鍵 System.out.println(map.values()); // 將map的值轉(zhuǎn)化為List List list = new ArrayList(map.values()); System.out.println(list); // 將map的值轉(zhuǎn)化為Set Set set = new HashSet(map.values()); System.out.println(set); |
6.list轉(zhuǎn)數(shù)組
1
2
3
4
5
|
List list = Arrays.asList( "a" , "b" ); System.out.println(list); String[] arr = (String[])list.toArray( new String[list.size()]); System.out.println(Arrays.toString(arr)); |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://www.cnblogs.com/tuojunjie/p/6222849.html