What is the difference between them?
l is an arraylist of Integer type.
version 1:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i);
}
return a;
version 2:
int[] a = new int[l.size()];
for (int i = 0; i < l.size(); i++) {
a[i] = l.get(i).intValue();
}
return a;
l.get(i);will returnIntegerand then callingintValue();on it will return the integer as typeint.Converting an
inttoIntegeris called boxing.Converting an
Integertointis called unboxingAnd so on for conversion between other primitive types and their corresponding Wrapper classes.
Since java 5, it will automatically do the required conversions for you(autoboxing), so there is no difference in your examples if you are working with Java 5 or later. The only thing you have to look after is if an
Integeris null, and you directly assign it tointthen it will throw NullPointerException.Prior to java 5, the programmer himself had to do boxing/unboxing.