Autoboxing is a new feature offered in the Tiger (1.5) release of Java SDK. In sort auto boxing is a capability to convert or cast between object wrapper and it's primitive type.
Java version 1.5 we were offered a new feature in the Java Language, which automate this process, this is call the Autoboxing. When we place an int value into a collection it will be converted into an Integer object behind the scene, on the other we can read the Integer value as an int type. In most way this simplify the way we code, no need to do an explicit object casting.
You no longer have to take your primitive data types and turn them into objects when using them in a collection. Collections do not like primitive data types.
The collections classes are designed to store objects. Consider the following simple example of storing int values from 0 to 9 in an ArrayList:
import java.util.ArrayList;
public class Autoboxing
{ public static void main(String[] args) {
ArrayList list = new ArrayList();
for(int i = 0; i <>
list.add(i);
}
}
}
The comparable program for J2SE 1.4.2 would be the following:
import java.util.ArrayList;
public class ManualBoxing {
public static void main(String[] args) {
ArrayList list = new ArrayList();
for(int i = 0; i <>
list.add(new Integer(i));
}
}
}
With ManualBoxing you need to explicitly create the Integer object using list.add(new Integer(i)). Contrast that with Autoboxing, where the int i is autoboxed to an Integer object in the line list.add(i).
Autoboxing works well with other new J2SE 5.0 features. For example, the autoboxing feature allows seamless integration between generic types and primitive types. In the ManualBoxing example, the elements of the ArrayList are of type Object. By comparison, in the Autoboxing example, the elements of list are of type Integer.
No comments:
Post a Comment