In Java SE 5, autoboxing was introduced to automatically convert between primitives and primitive wrappers. Primitives means basic types such as int, short, long, etc. Corresponding wrappers are Integer, Short, Long, and… nope, no Etc. To understand this, let’s look at the interaction between primitive and their wrappers before SE 5.
int originalInt = 3;
// convert primitive 3 to wrapper
Integer intWrapper = new Integer(originalInt);
// convert wrapper to primitive
int intPrimitive = intWrapper.intValue();
// store primitive in ArrayList
ArrayList list = new ArrayList();
list.add(new Integer(3));
// retrieve primitive in ArrayList
Integer wrapped = (Integer)list.get(0);
int unwrapped = wrapped.intValue();
// short-cut to retrieve primitive, less readable
int fastUnwrap = ((Integer)list.get(0)).intValue();
As shown above, a common usage of wrappers is when you need to store primitives as Objects. The ArrayList accepts an Object to be added, so it cannot add an int directly. However, we can make use of an Integer wrapper to put the number into the ArrayList, and take it out subsequently.
With SE 5, Java automatically generates necessary code to convert between primitives and wrappers during compilation. Let’s look at the new way with Autoboxing.
int originalInt = 3;
// convert primitive 3 to wrapper - Java will auto-convert
Integer intWrapper = originalInt;
// convert wrapper to primitive - Java will auto-convert
int intPrimitive = intWrapper;
// store primitive in ArrayList - generics added
ArrayList list = new ArrayList();
list.add(3);
// retrieve primitive in ArrayList
int unwrapped = list.get(0);
As you can see, all the scenarios have been simplified. Adding generics allows direct adding and retrieval of primitive types without any casting or wrapping. Despite being a useful convenient feature, programmers who pick up SE 5 directly without knowledge of the old way may not understand the rationale or even find it confusing (especially the ArrayList