In Java (1.4) to use a primitive value where an object is required, you need a “wrapper�
aVector.add(new Integer(123));
Similarly, you can’t use an object where a primitive is required, you need to “unwrap� it
int n = ((Integer)aVector.lastElement()).intValue();
In Java 5 it goes automatically:
Vector<Integer> aVector = new Vector<Integer>();
myVector.add(123);
int n = aVector.lastElement();
Notes:
Integer x = 6;
Integer y = 2*x;
generates the same byte code as
Integer x = Integer.valueOf(6);
Integer y = Integer.valueOf(2 * x.intValue());
Also for:
public static void doit(Integer i) {…}
Int k = 30;
doit(k);
Other extensions make this as transparent as possible
For example, control statements that previously
required a boolean (if, while, do-while) can now take
a Boolean
There are some subtle issues with equality tests,
Though
When there is an “impedance mismatch�
between reference types and primitives
─ For example, numerical value into collection
• Not appropriate for scientific computing
─ performance sensitive numerical code
• An Integer is not a substitute for an int
When to Use Autoboxing
• When there is an “impedance mismatch�
between reference types and primitives
─ For example, numerical value into collection
• Not appropriate for scientific computing
─ performance sensitive numerical code
• An Integer is not a substitute for an int