How do I convert int[]
into List
in Java?
Of course, I\'m interested in any other answer than doing it in a loop, item by it
give a try to this class:
class PrimitiveWrapper extends AbstractList {
private final T[] data;
private PrimitiveWrapper(T[] data) {
this.data = data; // you can clone this array for preventing aliasing
}
public static List ofIntegers(int... data) {
return new PrimitiveWrapper(toBoxedArray(Integer.class, data));
}
public static List ofCharacters(char... data) {
return new PrimitiveWrapper(toBoxedArray(Character.class, data));
}
public static List ofDoubles(double... data) {
return new PrimitiveWrapper(toBoxedArray(Double.class, data));
}
// ditto for byte, float, boolean, long
private static T[] toBoxedArray(Class 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;
}
}
testcase:
List ints = PrimitiveWrapper.ofIntegers(10, 20);
List doubles = PrimitiveWrapper.ofDoubles(10, 20);
// etc