Sorting a Collection

One of the drawbacks of Vector when it was first introduced was that it provided no way to sort its elements. You were left to either write your own sort routines or incorporate a set of third-party classes to provide what is typically a key function in most applications. Fortunately, the collections framework addressed the issue of sorting directly and provided the functionality as part of the API.

The Comparable Interface

Throughout this chapter, classes have been discussed that make use of the natural ordering of objects. A class has a natural ordering when it implements the java.lang.Comparable interface:

public interface Comparable {
  public int compareTo(Object o);
}

The compareTo method of this interface is implemented ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.