安利一个较全的集合与数组的相互转换

集合转数组:

public void Array() {
 List list = new ArrayList();
  []  Array1 = list.toArray();
 String[] array1 = list.toArray(new String[list.size()]);
 
 Set set = new HashSet();
  []  Array2 = set.toArray();
 String[] array2 = set.toArray(new String[set.size()]);
}

数组转集合:

Integer[] numbers = {7, 7, 8, 9, 10, 8, 8, 9, 6, 5, 4};
List list = Arrays.asList(numbers);
Set set = new HashSet(list);

注意:对于int[]数组不能直接这样做,因为asList()方法的参数必须是对象。应该先把int[]转化为Integer[]。对于其他primitive类型的数组也是如此,必须先转换成相应的wrapper类型数组。

 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);
收藏 打印