Skip to main content

Eye of the Tiger - Generics in J2SE 1.5

Posted by sam_dalton on December 3, 2003 at 4:04 AM PST

Once again (actually it seems like an age since the last one), a new incarnation of the J2SE is nearing release. This time there seems to be a lot of completely new language features (that is not to say that previous releases have been insignificant).

Below is a list of major features:

  • Generics
  • Enhanced for loop
  • Autoboxing/unboxing
  • Typesafe enums
  • Static import
  • Metadata

As you can see these are a fair number of totally new (to Java anyway) features, but what do they all mean? Well starting at the top, here is a brief description of Generics:

static void dumpSam(Collection c) {
    for (Iterator i = c.iterator(); i.hasNext(); ) {
        String s = (String);
        if (s.indexOf("sam") > 0)

The above code dumps the items of a collection that contain the word "sam" to the screen using 1.4 syntax. Nothing much wrong with it, except that the cast is ugly, and there is the potential of a ClassCastException at runtime. Now if we look at how this might be done usign generics, we see that is is much prettier, and also guaranteed not to fail at runtime:

static void dumpSam(Collection<String> c) {
    for (Iterator<String> i = c.iterator(); i.hasNext(); ) {
        String s =;
        if (s.indexOf("sam") > 0)

We can see from the signature of the method (static void dumpSam(Collection<String> c)) that the collection must only contain Strings, and also from the iterator that it will only return Strings. If you try to pass in a collection containing anything else, the program will simply fail to compile.

Now this may all look a little alien to start with, but I am sure once we get used to seeing generics it will actually be far clearer than code written with casts. What's more, you can try out generics now by downloading the prototype implementation of the spec.

I will blog about some of the other new Java 1.5 features at a later date (once I have had a chance to play with them.)

Related Topics >>