0

Java AutoBoxing

Posted by Guillermo GarcĂ­a on 6:49 PM in , ,
How many times you have seen something like this?

int primitive = 1;
ArrayList list = new ArrayList();

list.add(new Integer(primitive));

or like this?

int primitive = 1;
Integer object = new Integer(1);

if(object.intValue() == primitive){
//Do something
}

Your code could get very messy if you are using a lot of wrappers-primitive comparisons, or if you are using Collections to storage primitive values. You must always do the "boxing" or "unboxing" of the values to do what you want.

That was true until Java 5. This version includes a very nice, easy going and, soon obvious feature: Autoboxing.

Think of Autoboxing as an automatic transformation of a primitive in a wrapper and vice versa. So, now you won't to spoil your code with a messy "boxing"/"unboxing" sentences.

The previous examples could be coded like this:

int primitive = 1;
ArrayList list = new ArrayList();

list.add(primitive); //Autoboxing to a wrapper

and like this:


int primitive = 1;
Integer object = new Integer(1);

if(object == primitive){ //Autoboxing to a primitive
//Do something
}

Simpler right? Now, I have a question for you ... why did I say that the object is unboxed to a primitive and not in the contrary? It's simple, if you box the primitive into a wrapper, you will get two wrappers, and when you compare two wrapper (Java objects) with equal, you are comparing the reference, not the value (Being aware of this will set you free)

0 Comments

Copyright © 2009 ggarciao.com
- Cup of Java -
All rights reserved.