Autoboxing/Unboxing

The problem with the collection API is that you cannot put primitive data types into it. Instead, you must use their object counter parts. For instance, you have to use the Integer class and convert back and forth, like this:

int rate = 3;Vector vec = new Vector();vec.addElement(new Integer(rate));//   do what ever int result = ((Integer)vec.lastElement()).intValue();

The following code uses the new features of JDK 1.5 for greater ease of development. In it, the compiler takes all the responsibility of converting back and forth. Moreover, this code is a lot more concise:

            int rate = 3;                Vector vec = new Vector();                vec.addElement(rate);                  // don't need to do conversion//  do your implementation                  int result = vec.lastElement();   // don't need to convert here as well

Autoboxing and unboxing allows you to focus on your task rather than the language itself.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: