/* * *NOTE*: As-is, this program WILL NOT compile. It will if you * disable the second add() line. * * TGn02: Java After Generics. In Java 1.5 (aka Java 5.0), * the concept of generics was introduced. Generics permits * programmers to declare collections that are meant to hold a specific * kind of object by providing a type with the object. These are known * as parameterized types or generics. Because the compiler now knows * which variety of object a collection holds, casting on retrieval is * not necessary. Further, should you try to mix object types within * the collection, Java can let you know about the problem. * * The example requires Java 1.5 (5.0) or later. */ import java.io.*; import java.util.*; public class TGn02 { public static void main (String [] args) { ArrayList myList; String phrase; myList = new ArrayList(); myList.add("After Generics"); // Place String reference in index 0 myList.add(new Double(3.14159)); // *Try* to place Double in index 1 phrase = myList.get(0); // Retrieve object reference; no cast! System.out.printf("%s\n",phrase); } }