I want to convert the primitive type array to its respective boxed one, for example if I have an array of type int[]
I would like to convert it to Integer[]
, and the same is to apply on long[], byte[], boolean[]
, etc...
I came up with this:
public static Integer[] toBoxedArray(int[] array) {
Integer[] boxedArray = null;
if (array != null) {
boxedArray = new Integer[array.length];
for (int i = 0; i < array.length; i++) {
boxedArray[i] = array[i];
}
}
return boxedArray;
}
The above method is repeated (a polymorphism) for all the primitive types.
The use of these methods requires many conditional blocks:
public static List castArrayToList(Object array) {
List list = null;
if (array instanceof int[]) {
list = Arrays.asList(toBoxedArray((int[]) array));
} else if (array instanceof long[]) {
list = Arrays.asList(toBoxedArray((long[]) array));
} else if (array instanceof byte[]) {
list = Arrays.asList(toBoxedArray((byte[]) array));
} else if (array instanceof boolean[]) {
list = Arrays.asList(toBoxedArray((boolean[]) array));
} else if (array instanceof float[]) {
list = Arrays.asList(toBoxedArray((float[]) array));
} else if (array instanceof short[]) {
list = Arrays.asList(toBoxedArray((short[]) array));
} else if (array instanceof double[]) {
list = Arrays.asList(toBoxedArray((double[]) array));
} else if (array instanceof char[]) {
list = Arrays.asList(toBoxedArray((char[]) array));
} else if (array instanceof Collection) {
list = new ArrayList((Collection) array);
}
return list;
}
My question is this: is there a way to reduce the number of if
's in the castArrayToList
method ?
EDIT
the castArrayToList
method takes Object
as parameter, since the input comes from a reflective invokation.