Java Reference
In-Depth Information
Table 7-3. Comparable compared with Comparator
Interface name
Description
Method(s)
java.lang.Comparable<T> Provides a natural order to objects. Written in the class whose
objects are being sorted.
int compareTo(T
o);
java.util.Comparator<T> Provides total control over sorting objects of another class.
Standalone; pass to sort() method or Collection constructor.
Implements Strategy Design Pattern.
int compare(T o1,
T o2); boolean
equals(T c2)
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 sor-
ted 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, though this may or may not be faster overall, de-
pending on your data and how you choose to keep it sorted. You can keep it sorted either
manually or by using a TreeSet or a TreeMap . First, here is some code from a call tracking
program that I first wrote on the very first public release of Java (the code has been modern-
ized slightly!) to keep track of people I had extended contact with. Far less functional than a
Rolodex, my CallTrack program maintained a list of people sorted by last name and first
name. It also had the city, phone number, and email address of each person. Here is a very
small portion of the code surrounding the event handling for the New User push button:
public
public class
class CallTrack
CallTrack {
/** The list of Person objects. */
protected
protected List < Person > usrList = new
new ArrayList <>();
Search WWH ::




Custom Search