ProblemYou are tired of typing code like new Integer(i) and intObj.intValue( ) to convert back and forth between primitives and Object Wrappers. SolutionUse the JDK 1.5 compiler; it will AutoBox and AutoUnbox for you. DiscussionThere'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.javapublic 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). |