我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
当前回答
/* Integer[] to List<Integer> */
Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
List<Integer> arrList = new ArrayList<>();
arrList.addAll(Arrays.asList(intArr));
System.out.println(arrList);
/* Integer[] to Collection<Integer> */
Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
Collection<Integer> c = Arrays.asList(intArr);
其他回答
没有将int[]转换为List<Integer>作为数组的快捷方式。asList不处理装箱,只会创建一个List<int[]>,这不是你想要的。你必须创建一个实用方法。
int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>(ints.length);
for (int i : ints)
{
intList.add(i);
}
下面是一个将数组转换为数组列表的通用方法
<T> ArrayList<T> toArrayList(Object o, Class<T> type){
ArrayList<T> objects = new ArrayList<>();
for (int i = 0; i < Array.getLength(o); i++) {
//noinspection unchecked
objects.add((T) Array.get(o, i));
}
return objects;
}
使用
ArrayList<Integer> list = toArrayList(new int[]{1,2,3}, Integer.class);
也来自番石榴图书馆…com.google.common.primitives.Ints:
List<Integer> Ints.asList(int...)
那么这个呢:
Int [] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);
/* Integer[] to List<Integer> */
Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
List<Integer> arrList = new ArrayList<>();
arrList.addAll(Arrays.asList(intArr));
System.out.println(arrList);
/* Integer[] to Collection<Integer> */
Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
Collection<Integer> c = Arrays.asList(intArr);