我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
我如何转换int[]到列表<整数>在Java?
当然,我对任何其他答案都感兴趣,而不是一项一项地循环计算。但如果没有其他答案,我将选择这个答案作为最好的答案,以表明这个功能不是Java的一部分。
当前回答
如果你愿意使用第三方库,这将在Eclipse Collections中工作:
int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);
注意:我是Eclipse Collections的提交者。
其他回答
那么这个呢:
Int [] a = {1,2,3}; Integer[] b = ArrayUtils.toObject(a); List<Integer> c = Arrays.asList(b);
同样值得一看的是这个bug报告,它以“Not a defect”和以下文本结尾:
“自动装箱整个数组不是指定的行为,这是有充分理由的。 对于大型阵列来说,它可能会非常昂贵。”
下面是一个将数组转换为数组列表的通用方法
<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);
最佳拍摄:
**
* Integer modifiable fix length list of an int array or many int's.
*
* @author Daniel De Leon.
*/
public class IntegerListWrap extends AbstractList<Integer> {
int[] data;
public IntegerListWrap(int... data) {
this.data = data;
}
@Override
public Integer get(int index) {
return data[index];
}
@Override
public Integer set(int index, Integer element) {
int r = data[index];
data[index] = element;
return r;
}
@Override
public int size() {
return data.length;
}
}
支持get和set。 无内存数据复制。 不要在循环中浪费时间。
例子:
int[] intArray = new int[]{1, 2, 3};
List<Integer> integerListWrap = new IntegerListWrap(intArray);
List<Integer> integerListWrap1 = new IntegerListWrap(1, 2, 3);
如果你愿意使用第三方库,这将在Eclipse Collections中工作:
int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);
注意:我是Eclipse Collections的提交者。