/* * TGn04: After Autoboxing/Unboxing. Because of generics, Java knows * what type of objects are in ArrayLists and other collections. With * that knowledge, on an insertion it can automatically make a Double * object for a double value, saving the programmer the trouble. This * step is called `autoboxing'. The resulting code is shorter and * easier to read. * * The benefits are also realized when a value is extracted from a * collection; Java can pull the value from a wrapper automatically. * This is called `unboxing'. * * Note that when ArrayList is used in the code, its type parameter is * Double, not double. ArrayList still holds only object references; * asking it to directly reference a base type, such as double, is still * improper. Java 1.5 (5.0) just does the wrapping and unwrapping for * you; it doesn't change the collection-of-objects nature of ArrayList. * * Also note the formatting of the floating point value in the printf() * call. This is a convenient way (borrowed from the C language) to * round output to a particular number of decimal places. * * It should be no surprise that, if compiled with a Java 1.4 or earlier * compiler, this code will generate errors. */ import java.io.*; import java.util.*; public class TGn04 { public static void main (String [] args) { ArrayList myList; // We want a collection of Doubles double temperature; myList = new ArrayList(); // The new matches the variable myList.add(98.6); // plain ol' double is `autoboxed' temperature = myList.get(0); // `unbox' the object automatically System.out.printf("Someone's temperature is %.2f degrees F.\n", temperature); } }