devxlogo

Autoboxing/Unboxing

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.

See also  5 Tips to Manage a Remote Workforce
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist