如何在Java中将int []转换为List <Integer>？

``````List<Integer> Ints.asList(int...)
``````
Question

``````int[] a = {1, 2, 3};
List<Integer> integers = IntLists.mutable.with(a).collect(i -> i);
Assert.assertEquals(Lists.mutable.with(1, 2, 3), integers);
``````

Arrays.asList将不会像其他一些答案所期望的那样工作。

``````int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List lst = Arrays.asList(arr);
System.out.println(lst.size());
``````

``````List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
``````

``````String str[] = { "Homer", "Marge", "Bart", "Lisa", "Maggie" };
List<String> lst = Arrays.asList(str);
``````

``````   /* Integer[] to List<Integer> */

Integer[] intArr = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
List<Integer> arrList = new ArrayList<>();
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);
``````

``````public List<Integer> myWork(int[] array) {
return Arrays.asList(ArrayUtils.toObject(array));
}
``````

ArrayUtils来自commons-lang :)

``````class PrimitiveWrapper<T> extends AbstractList<T> {

private final T[] data;

private PrimitiveWrapper(T[] data) {
this.data = data; // you can clone this array for preventing aliasing
}

public static <T> List<T> ofIntegers(int... data) {
return new PrimitiveWrapper(toBoxedArray(Integer.class, data));
}

public static <T> List<T> ofCharacters(char... data) {
return new PrimitiveWrapper(toBoxedArray(Character.class, data));
}

public static <T> List<T> ofDoubles(double... data) {
return new PrimitiveWrapper(toBoxedArray(Double.class, data));
}

// ditto for byte, float, boolean, long

private static <T> T[] toBoxedArray(Class<T> boxClass, Object components) {
final int length = Array.getLength(components);
Object res = Array.newInstance(boxClass, length);

for (int i = 0; i < length; i++) {
Array.set(res, i, Array.get(components, i));
}

return (T[]) res;
}

@Override
public T get(int index) {
return data[index];
}

@Override
public int size() {
return data.length;
}
}
``````

``````List<Integer> ints = PrimitiveWrapper.ofIntegers(10, 20);
List<Double> doubles = PrimitiveWrapper.ofDoubles(10, 20);
// etc
``````

“整个数组的自动装箱并不是特定的行为，理由很多，对于大型数组来说，这可能是非常昂贵的。”

``````int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));

List<Integer> list = new ArrayList<>();
System.out.println(list);
``````

``````[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
``````