J2SE New Features - Generics

J2SE 5.0 gives developers a whole load of new features – too many to list here, but a complete list is given at http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html

Generics is one of the best new features that has been added to J2SE 5.0 and they are incredibly easy to use! So what is Generics? Well, to put it simply, Generics gives you type safety on collections, so you can create collections that will only hold a specific type. Furthermore, when you get an object out of a collection using Generics, you don’t need to cast it to the relevent type – this is done automatically for you. This is best shown with a small example.

// Declare an array list called items that can only hold strings.
Collection items = new ArrayList();

// Add a couple of strings to the collection.
items.add("String 1");
items.add("String 2");

// Declare a 'String' iterator to loop through the collection.
Iterator iter = items.iterator();
while (iter.hasNext()) {
    // Get a value from the collection - note there is no need to cast it.
    String value = iter.next();