COP 3530 Section U02 Spring 2015 The ArrayList Class: Raw and Generic ==================================== I. The Program: // an example of generics import java.util.ArrayList; public class Generics3 { // we use array lists public static void main(String[] args) { System.out.println("Array Lists: Raw Type and Generic"); System.out.println("=================================\n\n"); System.out.println("We use an untyped array list."); System.out.println("In it we put an integer, a string, and a real number."); ArrayList junk = new ArrayList(); junk.add(10); junk.add("Papa Bill"); junk.add(3.5); System.out.println("We try to retrieve the item at index 0 as an integer."); int i = (Integer) junk.get(0); System.out.println("It is " + i); System.out.println("We try to retrieve the item at index 1 as a decimal."); try { double x = (Double) junk.get(0); } catch( ClassCastException e) { System.out.println("We get " + e); } // Now let us use generics System.out.println("\nNow let us use generics."); System.out.println("We form an array list of strings and put the names " + "\nPapa Bill, Grandpa Smith, Poco Pelo."); ArrayList names = new ArrayList<>(); names.add("Papa Bill"); names.add("Grandpa Smith"); names.add("Poco Pelo"); System.out.println("The name as index 1 is " + names.get(1) + "."); } } II. The Output: run: Array Lists: Raw Type and Generic ================================= We use an untyped array list. In it we put an integer, a string, and a real number. We try to retrieve the item at index 0 as an integer. It is 10 We try to retrieve the item at index 1 as a decimal. We get java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double Now let us use generics. We form an array list of strings and put the names Papa Bill, Grandpa Smith, Poco Pelo. The name as index 1 is Grandpa Smith BUILD SUCCESSFUL (total time: 0 seconds)