Java 5: Generics

This will be included on the 2007 AP exam...

The java.util classes allow you to say what type of things are in the collection. ArrayList is one such class.

ArrayList<String> students = new ArrayList<String>();
students.add("John");    students.add("Paul");
students.add("George");  students.add("Ringo");
for(int i = 0; i < students.size(); i++) {
    String name = students.get(i);
    System.out.println(name);
}
Before, you would have to write this:
ArrayList students = new ArrayList();
students.add("John");    students.add("Paul");
students.add("George");  students.add("Ringo");
for(int i = 0; i < students.size(); i++) {
    String name = (String) students.get(i);   // Note the cast!
    System.out.println(name);
}

Generics have two major advantages.

(next)