我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
当前回答
也来自番石榴图书馆…com.google.common.primitives.Ints:
List<Integer> Ints.asList(int...)
其他回答
下面是一个将数组转换为数组列表的通用方法
<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);
那么这个呢:
Int [] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);
int[] arr = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
看到这个
没有将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);
}
同样值得一看的是这个bug报告,它以“Not a defect”和以下文本结尾:
“自动装箱整个数组不是指定的行为,这是有充分理由的。 对于大型阵列来说,它可能会非常昂贵。”