Avoiding the Urge to Sort

Problem

Your data needs to be sorted, but you don’t want to stop and sort it periodically.

Solution

Not everything that requires order requires an explicit sort operation. Just keep the data sorted at all times.

Discussion

You can avoid the overhead and elapsed time of an explicit sorting operation by ensuring that the data is in the correct order at all times. You can do this manually or, in Java 2, by using a TreeSet or a TreeMap . First, some code from a call tracking program that I first wrote on JDK 1.0 to keep track of people I had extended contact with. Far less functional than a Rolodex, my CallTrak program maintained a list of people sorted by last name and first name. For each person it also had the city, phone number, and email address. Here is a portion of the code that was the event handler for the New User push button:

/** The list of User objects. */
Vector usrList = new Vector(  );
/** The scrolling list */
java.awt.List visList = new List(  );
/** Add one (new) Candidate to the lists */
protected void add(Candidate c) {
    String n = c.lastname;
    int i;
    for (i=0; i<usrList.size(  ); i++)
        if (n.compareTo(((Candidate)(usrList.elementAt(i))).lastname) <= 0)
            break;
        visList.add(c.getName(  ), i);
        usrList.insertElementAt(c, i);
        visList.select(i);      // ensure current
    }

This code uses the String class compareTo(String) routine. This has the same name and signature as the compareTo(Object) in Comparable, but was added to the String class in JDK 1.1, before the ...

Get Java Cookbook 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.