Java 5.0 Generics - The Beauty of Autboxing and Unboxing
Finally, now I get to use Java 5.0 compliancy when compiling; last year at work I was still stuck on 1.4 for compatibility reasons. Some of the nice new features are:
- Generics & auto boxing/unboxing
- Enhanced for loops (.NET style)
- Proper typesafe ‘enums’
- A new ’static’ keyword import
- Metadata
From time to time I will post examples of using some of the new features. For now, I’ll give a brief introduction to Generics.The old wayPrior to JDK 1.5 and traditionally, Java programmers were always plagued with problems associated with primitives, wrapper classes and collections. This stems from the basic problem of all objects in Java descending from the root class, Object. A common problem is trying to store a primitive in a collection (where collections traditionally store ‘Objects’). The way around this is to use one of the appropriate wrapper class; Double for double, Integer for int and so on. Having to ‘box’ a primitive in one of the wrapper objects is a real PITA as it requires an extra step, is slower and clutters up code.Here is an example…
LinkedList aList = new LinkedList(); aList.addFirst(new Integer(5)); aList.addFirst(new Integer(10)); aList.addFirst(new Integer(15));
What’s worse, is it is not type safe. Because it is stored as an Object, the programmer must ensure that they can safely downcast to an appropriate class, unbox and retrieve the value. Having to do this is ugly.
Iterator it = aList.iterator(); while (it.hasNext()) { Object o = it.next(); if (o instanceof Integer) { Integer aInt = (Integer)o; int myInt = aInt.intValue(); // do something with myInt }}
Fast track to Java 5.0 The new way
The syntax looks like this
LinkedList<E> aList = new LinkedList<E>();
…where
LinkedList<Integer> aList = new LinkedList<Integer>(); aList.addFirst(5); aList.addFirst(10); aList.addFirst(15); for (int myInt : aList) {System.out.println(myInt);}
So you can see it automatically unboxes the primitve int value for you. I’m not going to go into the enhanced for loops right now and will save that for another time.So what does generics achieve? Cleans up code a bit by removing all the down casts you would normally perform. In some cases, removes type checking. Gives you type safe checking at compile time rather then finding out a run time. One con to this obviously is because you have said you will only store Integers in it, you cannot store multiple types of objects in it like you could have done previously. In my opinion, the pros far outweight the cons.

November 20th, 2008 at 8:03 am
Very interesting article, i bookmarked your blog
Best regards