Recipe 8.4 Let Java Convert with AutoBoxing and AutoUnboxing


Problem

You are tired of typing code like new Integer(i) and intObj.intValue( ) to convert back and forth between primitives and Object Wrappers.

Solution

Use the JDK 1.5 compiler; it will AutoBox and AutoUnbox for you.

Discussion

There's a reason they call it automatic boxing: you don't have to do any work. The 1.5 compiler is finally able to figure out how to convert back and forth between primitives and their wrappers. Example 8-6 shows converting from a primitive int value to an Integer needed in a method call.

Example 8-6. AutoboxDemo.java
public class AutoboxDemo {     public static void main(String[] args) {         int i = 42;         foo(i);     }     public static void foo(Integer i) {         System.out.println("Object = " + i);     } }

This code compiles and runs on JDK 1.5 (but only with the -source 1.5 option). Notice what happens when we omit that option:

C:\ian\javasrc\structure1.5>javac AutoboxDemo.java AutoboxDemo.java:4: foo(java.lang.Integer) in AutoboxDemo cannot be applied to (int)                 foo(i);                 ^ 1 error C:\ian\javasrc\structure1.5>javac -source 1.5 AutoboxDemo.java C:\ian\javasrc\structure1.5>java AutoboxDemo Object = 42 C:\ian\javasrc\structure1.5>

The resulting class file does not run in a JDK 1.4 implementation because it depends on a new method signature in the Integer class, notably valueOf(int i).



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net