Java 5 Generics

No Gravatar

Here’s a quick example of the difference between Java 1.4 Iterators and Java 5 generics.

Here’s 1.4:


List myList = new ArrayList();

myList.add(new Person("John Melton"));
myList.add(new Person("Bill Mares"));

for (Iterator it=myList.iterator(); it.hasNext(); ) {
    Person person = (Person) it.next();
    System.out.println(person);
}

Now the Java 5 generics version:


List<Person> myList = new ArrayList<Person>();

myList.add(new Person("John Melton"));
myList.add(new Person("Bill Mares"));

for (Person person : myList) {
    System.out.println(person);
}

See – very pretty. You just add those fun angle brackets (<>) to denote generics, and the code is cleaned up quite a bit. In my experience, the returns on beauty only get greater the more code you write. There’s also some great templating features with generics to make generic processing procedures very flexible. I love the syntactic sugar … mmmm.

Happy coding!

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *