Sunday, July 8, 2007

Collection sort method and Java Generics - how to

I was looking into one of my old Java source files and found out that I was struggling with correct syntax of Collection.sort() method using Generics when Java 1.5 was released.

Correct syntax is Collection.<CustomType>sort().

[Excerpt taken from 1]
The sort static method is designed to work with a class T that implements Comparable on T or some superclass of T [see 3], e.g. Object. (Infuriatingly, generics use the term extends [see 2] when they really mean implements).

[2] Collections.sort()
[3] Comparable.compareTo()

No comments: