Generic Java

I have been using Java 1.5, or as Sun calls it Java 5.0, with Eclipse 3.1.0. One of the kewl new features of Java 1.5 is generics (which C++ has had for over ten years). If you use generics with a list you don’t have to keep casting to an expected object. When you cast you pretty much are guessing about the types contained in a collection. If you use generics you can guarantee the type of in a list or hash map, in fact it is used by the compiler for type checking. To get started lets create a list using generics:

List<String> myList = new ArrayList<String>();
// fill my list with string objects
for(int i=0; i < myList.size(); i++)  {
	String item = myList.get(i);
	System.out.println(item);
}

See. No cast required. Here is the same snippet using the new for/in loop to mix things up a bit.

List<String> myList = new ArrayList<String>();
// fill my list with strings objects...
for(String item : myList)  {
	System.out.println(item);
}

To illustrate Java generics with another example, here is a snippet of code that uses a map instead of a list.

Map<String, String> myMap = new HashMap<String, String>();
// fill my map with string key and value objects...
Iterator<String> i = myMap.keySet().iterator()
while(i.hasNext)
	String key = i.next();

Again, the benefits of using Java generics is compile type checking so that you won’t be surprised with a ClassCastException at runtime during an important demo.