The
compareTo method is the sole member of the
Comparable interface, and is not a member of
Object. However, it is quite similar in nature to
equals and
hashCode. It provides a means of fully ordering objects.
Implementing
Comparable allows
- calling Collections.sort and Collections.binarySearch
- calling Arrays.sort and Arrays.binarySearch
- using objects as keys in a TreeMap
- using objects as elements in a TreeSet
The
compareTo method
needs to satisfy the following conditions. These conditions have the goal of allowing objects to be fully sorted, much like the sorting of a database result set on all fields.
- anticommutation : x.compareTo(y) is the opposite sign of y.compareTo(x)
- exception symmetry : x.compareTo(y) throws exactly the same exceptions as y.compareTo(x)
- transitivity : if x.compareTo(y)>0 and y.compareTo(z)>0, then x.compareTo(z)>0 (and same for less than)
- if x.compareTo(y)==0, then x.compareTo(z) has the same sign as y.compareTo(z)
- consistency with equals is highly recommended, but not required : x.compareTo(y)==0, if and only if x.equals(y) ; consistency with equals is required for ensuring sorted collections (such as TreeSet) are well-behaved.
One can greatly increase the performance of
compareTo by comparing first on items which are most likely to differ. When a class extends a
concrete Comparable class and adds a significant field, a correct implementation of
compareTo cannot be constructed. The only alternative is to use composition instead of inheritance. (A similar situation holds true for
equals. See
Effective Java for more information.)
Compare the various types of fields as follows :
- numeric primitive : use < and >. There is an exception to this rule: float and double primitives should be compared using Float.compare(float, float) and Double.compare(double, double). This avoids problems associated with special border values.
- boolean primitive : use tests of the form (x && !y)
- Object : use compareTo. (Note that possibly-null fields present a problem : while x.equals(null) returns false, x.compareTo(null) will always throw a NullPointerException)
- type-safe enumeration : use compareTo, like any Object
- collection or array : Comparable does not seem to be intended for these kinds of fields. For example, List, Map and Set do not implement Comparable. As well, some collections have no definite order of iteration, so doing an element-by-element comparison cannot be meaningful in those cases.
If the task is to perform a sort of items which are stored in a relational database, then it is usually much preferred to let the database perform the sort using the ORDER BY clause, rather than in code. An alternative to implementing
Comparable is passing
Comparator objects as parameters. Be aware that if a
Comparator compares only one of several significant fields, then the
Comparator is very likely not synchronized with
equals.
All primitive wrapper classes implement
Comparable. Note that
Boolean did not implement
Comparable until version 1.5, however.
Example:
import java.util.*;
import java.io.*;
public final class Account implements Comparable<Account> {
//Constructor
enum AccountType {CASH, MARGIN, RRSP};
public Account (
String aFirstName,
String aLastName,
int aAccountNumber,
int aBalance,
boolean aIsNewAccount,
AccountType aAccountType
) {
fFirstName = aFirstName;
fLastName = aLastName;
fAccountNumber = aAccountNumber;
fBalance = aBalance;
fIsNewAccount = aIsNewAccount;
fAccountType = aAccountType;
}
public int compareTo( Account aThat ) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if ( this == aThat ) return EQUAL;
if (this.fAccountNumber < aThat.fAccountNumber) return BEFORE;
if (this.fAccountNumber > aThat.fAccountNumber) return AFTER;
if (!this.fIsNewAccount && aThat.fIsNewAccount) return BEFORE;
if (this.fIsNewAccount && !aThat.fIsNewAccount) return AFTER;
int comparison = this.fAccountType.compareTo(aThat.fAccountType);
if ( comparison != EQUAL ) return comparison;
comparison = this.fLastName.compareTo(aThat.fLastName);
if ( comparison != EQUAL ) return comparison;
comparison = this.fFirstName.compareTo(aThat.fFirstName);
if ( comparison != EQUAL ) return comparison;
if (this.fBalance < aThat.fBalance) return BEFORE;
if (this.fBalance > aThat.fBalance) return AFTER;
assert this.equals(aThat) : "compareTo inconsistent with equals.";
return EQUAL;
}
@Override public boolean equals( Object aThat ) {
if ( this == aThat ) return true;
if ( !(aThat instanceof Account) ) return false;
Account that = (Account)aThat;
return
( this.fAccountNumber == that.fAccountNumber ) &&
( this.fAccountType == that.fAccountType ) &&
( this.fBalance == that.fBalance ) &&
( this.fIsNewAccount == that.fIsNewAccount ) &&
( this.fFirstName.equals(that.fFirstName) ) &&
( this.fLastName.equals(that.fLastName) );
}
@Override public int hashCode() {
int result = HashCodeUtil.SEED;
result = HashCodeUtil.hash( result, fAccountNumber );
result = HashCodeUtil.hash( result, fAccountType );
result = HashCodeUtil.hash( result, fBalance );
result = HashCodeUtil.hash( result, fIsNewAccount );
result = HashCodeUtil.hash( result, fFirstName );
result = HashCodeUtil.hash( result, fLastName );
return result;
}
private String fFirstName; private String fLastName; private int fAccountNumber;
private int fBalance;
private boolean fIsNewAccount;
private AccountType fAccountType;
public static void main (String[] aArguments) {
String text = "blah";
Integer number = new Integer(10);
System.out.println("false: " + text.equals(null));
System.out.println("false: " + number.equals(null) );
Account flaubert = new Account(
"Gustave", "Flaubert", 1003, 0,true, AccountType.MARGIN
);
Account flaubert2 = new Account(
"Guy", "Flaubert", 1003, 0, true, AccountType.MARGIN
);
Account flaubert3 = new Account(
"Gustave", "de Maupassant", 1003, 0, true, AccountType.MARGIN
);
Account flaubert4 = new Account(
"Gustave", "Flaubert", 2004, 0, true, AccountType.MARGIN
);
Account flaubert5 = new Account(
"Gustave", "Flaubert", 1003, 1, true, AccountType.MARGIN
);
Account flaubert6 = new Account(
"Gustave", "Flaubert", 1003, 0, false, AccountType.MARGIN
);
Account flaubert7 = new Account(
"Gustave", "Flaubert", 1003, 0, true, AccountType.CASH
);
System.out.println( "0: " + flaubert.compareTo(flaubert) );
System.out.println( "first name +: " + flaubert2.compareTo(flaubert) );
System.out.println( "last name +: " + flaubert3.compareTo(flaubert) );
System.out.println( "acct number +: " + flaubert4.compareTo(flaubert) );
System.out.println( "balance +: " + flaubert5.compareTo(flaubert) );
System.out.println( "is new -: " + flaubert6.compareTo(flaubert) );
System.out.println( "account type -: " + flaubert7.compareTo(flaubert) );
}
}
A sample run of this class gives:
>java -cp . Account
false: false
false: false
0: 0
first name +: 6
last name +: 30
acct number +: 1
balance +: 1
is new -: -1
account type -: -1