T
Thomas Hawtin
int can be auto-boxed into Integer in Tiger, but I want to convert
int[] to Integer[]. How to do that? Thanks.
static Integer[] box(int[] array) {
int num = array.length;
Integer[] boxed = new Integer[num];
for (int ct=0; ct<num; ++ct) {
boxed[ct] = Integer.valueOf(array[ct]);
}
return boxed;
}
Of course, changes made to the new array will not be updated in the old one.
To box arrays automatically would be even more confusing than
autoboxing. Consider:
Integer[] boxed = array;
boxed[0] = -1;
array[0] = 42;
System.out.println(boxed[0]);
If we assume autoboxing of arrays and array is an int[], then the code
will print -1. If array were an Integer[], then the code would print 42.
Alternatively, I guess you could produce (or find) a List<Integer>
implementation that backs to an int[] (a little like
java.util.Arrays.asList).
Tom Hawtin