You can’t put a primitive value into a collection since collections can only hold object references. To do so, you need to box primitive values into the appropriate wrapper class. When retriving, you get an object out of the collection and you need to unbox the it. Java 5 provides autoboxing and unboxing feature that eliminates the pain.
import java.util.ArrayList;
public class Autoboxing {
public static void main(String[] args) {
ArrayList list = new ArrayList ();
for(int i = 0; i < 10; i++){
list.add(i);
}
int sum = 0;
for ( Integer j : list){
sum += j;
}
System.out.printf("The sum is %d.", sum );
}
}
Comments