Java:集合與數組轉換


List,Set轉換為數組的方法。
toArray函數有兩種形式,一種無參數,一種帶參數,注意帶參數形式中,要指明數組的大小。

 

程序代碼:

1
2
3
4
5
6
7
8
9
public void convertCollectionToArray() {
 List list = new ArrayList();
 Object[] objectArray1 = list.toArray();
 String[] array1 = list.toArray(new String[list.size()]);
 
 Set set = new HashSet();
 Object[] objectArray2 = set.toArray();
 String[] array2 = set.toArray(new String[set.size()]);
}

 

 

 

 

 

 

 

反過來,數組轉換為List,Set。

1
2
3
4
5
 Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};
 // To convert an array into a Set first we convert it to a List. Next
 // with the list we create a HashSet and pass the list as the constructor.
 List list = Arrays.asList(numbers);
 Set set = new HashSet(list);

 

 

 

 

 

注意:對於int[]數組不能直接這樣做,因為asList()方法的參數必須是對象。應該先把int[]轉化為Integer[]。對於其他primitive類型的數組也是如此,必須先轉換成相應的wrapper類型數組。

1
2
3
4
5
6
7
8
 int[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};
 int size = numbers.length;
 Integer[] array = new Integer[size];
 for (int i = 0; i < numbers.length; i++) {
  Integer integer = numbers[i];
  array[i] = integer;
  }
 List list = Arrays.asList(array);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM