ArrayLists and Iterators
20. Autoboxing
Answer:
You would not expect
data.add( 44 );
to work, since it seems to be adding primitive data directly into the list of object references.
Autoboxing
Autoboxing
However, the statement is correct. The Java compiler expects an object reference. So when it sees
data.add( 44 );
it must supply an object reference for add()
, and automatically does the equivalent of this:
data.add( new Integer(44) );
This feature is called autoboxing and is new with Java 5.0.
Unboxing works the other direction. The int
inside a wrapper object is automatically extracted if an expression requires an int
. The following
int sum = 24 + data.get(1) ;
extracts the int
in cell 1 of data and adds it to the primitive int
24.
Question 20:
Does the following work?
Double value = 2.5; double sum = value + 5.7;