Monday, June 29, 2009

The extreme conservatism where I work had just about every Java project using JDK 1.4 until 2008, even though JDK 1.5 came out in 2003. New projects in 2008 started using JDK 1.6, but the existing projects continue to use JDK 1.4.

The best new feature of JDK 1.5 is generics. Most other people where I work don't seem to use generics beyond the collections classes, but even only that is huge improvement over JDK 1.4. I've only used generics beyond the collections classes sparingly at work -- just a handful of generic methods, where they make things simpler. I've made more extensive use of generics in my personal projects.

In JDK 1.4, one choice I've often had to make was whether an interface should use an array or a List. Arrays provide compile-time type checking, but Lists were usually much nicer to deal with. I usually decided on the array, and then using List.toArray() when passing or returning values. With generics, using a List is the clear choice.

Another thing is that, due a type-safety issue, arrays of parameterized types can't be instantiated, although they can be declared. A List of a parameterized type is just fine.
So,

C<T>[] array = new C<T>[size];

is illegal, but

List<C<T>> list = new List<C<T>>();

is fine. Of course, if, for some reason, an array really is needed,

class D extends C<T> { ... }

then an array of D can be used. (In all of these examples, T is a real class, and not a type parameter.)

No comments:

Post a Comment