Friday, July 28, 2006

Generics Rule!

So, I finally got around to learning some of the new features of Java 1.5 and .net 2.0. Among the many additions to the languages, one of my favorites is the concept of generics. A simple description is that generics are like templates in c++, only more powerful. Using generics, you can make a member or members of a class have an assignable type. In other words, you can make a new collection class that stores a specific type that is set by the person instantiating the class. The reason this is useful is that all of the accessor methods can return objects of that type, rather than returning objects and forcing the user to cast them. The other big benefit is that the compiler can enforce the type specification at compile time, not allowing incorrectly typed objects to be passed into the class. In addition, because the type specification is there, it is much easier to determine what a chunk of code does, what lists manage what types, etc.

Wow... so I just discovered an even cooler feature (really ought to start reading the feature lists). But anyhow, you can genericize an individual function just like you would a class. That is just friggin awesome.

So, long gone are the days of (OtherClass)((MyClass)list.get(i)).getInstances(), and welcome the days of list.get(i).getInstances().

huzzah