Autoboxing ใน java 5.0
posted on 09 Feb 2005 23:32 by somkiatAutoboxing
Autoboxing, introduced in Java 5, is the automatic conversion that Java makes between the primitive (basic) types and their corresponding object wrapper classes (eg, int and Integer, boolean and Boolean, etc). This sugar coating the avoids the tedious and hard-to-read casting typically required by Java Collections, which can not be used with primitive types.
Example
| With Autoboxing | Without Autoboxing |
|---|---|
int i; Integer j; i = 1; j = 2; i = j; j = i; | int i; Integer j; i = 1; j = new Integer(2); i = j.valueOf(); j = new Integer(i); |
Prefer primitive types
Use the primitive types where there is no need for objects for two reasons.
- Primitive types will not be slower than their corresponding wrapper types, and may be a lot faster.
- There can be some unexepected behavior involving
==(compare references) and.equals()(compare values). See the reference below for examples.
References
- Autoboxing surprises from J2SE 5 (www.theserverside.com/news/thread.tss?thread_id=27129)

#1 By plynoi แว่วศรี on 2005-02-10 23:06