Platinum Solutions Corporate Website


JDK

New features of JDK 5.0 - Generics

My favorite new feature of JDK 5.0 is Generics. Generics evolved from Templates in C++, but they are not entirely the same.  I will focus on the different applications of Generics and provide a brief explanation of how they are implemented using erasures.

 Introduction

Generics allow you to abstract over types.  The simplest example of demonstrating a Generic at work is with Collections.  The old way of getting an item out of a List looked something like this:

List l = new ArrayList();
l.add(someString);
l.add(anotherString);
for (Iterator listIterator = l.iterator(); listIterator.hasNext(); ) {
    String s = (String)listIterator.next();
}

This a trivial example of how we iterate through a list and how we have to cast the object we get out of the list.  Well, if we already know the type of object we are inserting into the list, then surely there must be a more precise way of extracting that object from your list.  This is part of the problem that Generics solve, here is what the same code looks like now with Generics (and the new for loop feature of JDK 5.0):

New features of JDK 5.0

The JDK 5.0 release has some new features and much improved enhancements to the JDK that developers should be happy and eager to take advantage of. I will attempt to showcase these improvements over the course of the next few weeks.

This week's new feature is Metadata (Annotations).
quote from Sun:

This language feature lets you avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a "declarative" programming style where the programmer says what should be done and tools emit the code to do it. Also it eliminates the need for maintaining "side files" that must be kept up to date with changes in source files. Instead the information can be maintained in the source file. Refer to JSR 175.