/* * TGn01: Java Before Generics. In Java versions prior to 1.5 (aka 5.0), * collection classes, such as ArrayList, had to hold plain old Object * references. Storing references to other kinds of objects isn't a * problem, as the adding of a String to the ArrayList shows. String * inherits from Object, making String a variety of Object, and ArrayList * is happy to reference any variety of Object. However, retrieving * the reference is a problem, because we're going in the other direction; * not every Object is a String. Using type casting, we have to tell Java * how to interpret the reference coming out of the get() method. Without * the cast, the compiler will flag that assignment as an error. * * If you compile this example with a 1.5 (5.0) or later version of Java, * you will get a warning from the compiler that "unchecked or unsafe * operations" are being used. This illustrates the need for generics: * Without them, the compiler was unable to help the programmer recognize * code that was potentially mixing object references in useless ways. * Now Java can recognize such situations and provide feedback. */ import java.io.*; import java.util.*; public class TGn01 { public static void main (String [] args) { ArrayList myList; String phrase; double value; myList = new ArrayList(); myList.add("Before Generics"); // Place String reference in index 0 myList.add(new Double(3.14159)); // Place Double reference in index 1 phrase = (String) myList.get(0); // Retrieve object reference and cast value = ((Double) myList.get(1)).doubleValue(); // Yuck! System.out.println(phrase); System.out.println(value); } }