| As wonderful as the primitive wrappers are, they often mean we end up creating a lot of objects (say with valueOf(int i) ), passing them into a list, and then putting them back into their primitive values again with intValue() ) when we drag them out of the list. Autoboxing is a feature new to Java 1.5 that takes care of this for us. Here's how it works in a nutshell . Create a primitive type. Pass it as an argument to a method that expects an Object. It magically works. The JVM converts the primitive to its corresponding wrapper on-the-fly for you. Autoboxing wouldn't be complete without auto-unboxing. As you might guess, this means that when you ask for a primitive directly from an Object wrapper, ye shall receive. Because this concept is fairly easy to understand and appreciate, let's go straight to the videotape. AutoboxAssigment.java package net.javagarage.autobox; public class AutoboxAssignment { public static void main(String[] args) { //whoa! primitive reference to object int bottlesOfBeer = new Integer(99); //the other way 'round Float temperature = 98.6f; } } This simple test shows that we can move effortlessly between primitives and their wrapper classes. | FRIDGE This is cool. It does not mean that you can start calling methods on 'primitives' as you can in some languages I won't mention (okay, C#). The old int.parse() trick won't play in this town . | | This is not license to do whatever wacky thing you want, however. You can't call methods on a primitive and expect it to know what you're trying to do. For example, say we try to call one of the Double wrapper class methods on a double primitive: double d = 45D; d.isNaN(); //Wrong!!! The compiler sez double cannot be dereferenced Just so you know it when you see it, let's try another test, a little more complicated. AutoboxDemo.java package net.javagarage.autobox; import java.util.*; public class AutoboxDemo { public static void main(String...args) { /**Make a map that holds String keys and Double values. Collection types can only hold objects, not primitives. */ Map<String,Double> weatherForecast = new TreeMap<String,Double>(); weatherForecast.put("Monday", 65); weatherForecast.put("Tuesday", 68); weatherForecast.put("Wednesday", 70); System.out.println(weatherForecast); } } This class creates a Map , which holds key/value pairs, and passes in double primitive values. Even though the Map only holds objects, they are converted on-the-fly and we don't have to deal with object creation for each one of those doubles ourselves . This functionality is convenient . I could show you the old, yucky way we had to do this, but I will spare you the gory details. They're just too awful If you enjoy torture, please refer to Chapter 18, "Casting and Type Conversions," for a little more on this. |