Comparable Objects: Giving Objects an Order

Comparable objects support a rule that places one object before, after, or at the same comparison position as another. You use this rule when sorting records or maintaining an ordered collection. An object's natural ordering is the default order defined by its class. In Java, a class advertises this capability through Comparable and implements it with compareTo.

Read the sign of a comparison

The call a.compareTo(b) compares the receiving object, a, with b. Its integer result describes their relative order. Write this result as c(a,b)c(a,b). The governing interpretation is:


sign⁡(c(a,b))={−1if a comes before b,0if a and b tie in the ordering,1if a comes after b.\operatorname{sign}(c(a,b))= \begin{cases} -1 & \text{if }a\text{ comes before }b,\\ 0 & \text{if }a\text{ and }b\text{ tie in the ordering},\\ 1 & \text{if }a\text{ comes after }b. \end{cases}


Returned value

Meaning

What it does not establish

Any negative integer

The receiver comes before the argument

A distance or number of positions

Zero

The objects tie under the ordering rule

That they are the same object

Any positive integer

The receiver comes after the argument

A distance or number of positions


A method may return -1, 0, and 1, but those are not the only permitted values. A result of -8 carries the same ordering information as -1.



Three objects are arranged by increasing key, with two objects sharing the same key.


Choose fields and resolve ties

The class designer chooses which fields determine natural order. For delivery records, the rule might compare estimated travel time first, then sequence number when travel times match. This is lexicographic ordering.


Example: Suppose delivery records store integer travel times in minutes and integer sequence numbers. The following method places shorter travel times first, then smaller sequence numbers:


Java
public int compareTo(Delivery other) {
    int byTime = Integer.compare(this.minutes, other.minutes);
    if (byTime != 0) {
        return byTime;
    }
    return Integer.compare(this.sequence, other.sequence);
}


The first nonzero result settles the comparison. Compare the secondary field only when the primary fields tie. Returning zero immediately after matching the primary fields would ignore the stated tie-breaking rule. Adding field differences can also fail because one difference may cancel another.


Use Integer.compare rather than subtracting unrestricted integer fields. Overflow can make a subtraction return the wrong sign. Reversing the arguments of a safe field comparison changes that field from ascending to descending order.

Make the ordering trustworthy

A valid comparison must behave consistently across objects. Swapping two unequal operands reverses the result's sign, although it need not preserve its magnitude. Transitivity means that if one object precedes a second and the second precedes a third, the first also precedes the third. Objects that tie must have matching comparison signs against every third object. An object also ties with itself.


Ordering ties and equality are related but separate. Java strongly recommends that compareTo returns zero exactly when equals returns true. A rule that compares only a person's age can tie two people whom equals distinguishes by identifier.



Keep ordering fields unchanged while an object occupies a position in an ordered structure, or remove and reinsert it after an update. Otherwise, its stored position may no longer match its comparison results.


What to remember

  • Interpret the sign, not the magnitude, of compareTo.
  • Apply tie-breakers in the stated priority order.
  • Check reversal, transitivity, and consistent treatment of ties.
  • Align ordering ties with equality when possible, and document exceptions.

Example: Ordering Laboratory Sample Requests

A laboratory orders sample requests by earlier deadline first, then smaller accession number first when deadlines tie. Deadlines are integer minutes after the laboratory opens; accession numbers are integer identifiers. A comparison key is the field or ordered combination of fields used to determine an object's comparison position. Here the key consists of deadline followed by accession number.


The request class implements its natural ordering with this method:


Java
public int compareTo(Request other) {
    int byDeadline = Integer.compare(this.deadlineMinutes,
                                     other.deadlineMinutes);
    if (byDeadline != 0) {
        return byDeadline;
    }
    return Integer.compare(this.accession, other.accession);
}


Assume the fields remain unchanged. The request labels identify separate records and are not additional comparison fields.


Request

Deadline after opening (min)

Accession number

L

18

405

M

12

430

N

18

401

P

18

405


a) Find the exact result of L.compareTo(M) and explain which request comes first.


First compare the deadlines. L's deadline is ________, and M's deadline is ________. The code evaluates Integer.compare(18, 12), which returns 1 because the receiver's deadline is later.


Because this result is nonzero, the method returns immediately. The accession numbers are not consulted, even though L has the smaller accession number.


The final result is 1, so M comes before L.


b) Find the exact result of L.compareTo(N) and explain how the tie-breaker works.


The primary comparison is Integer.compare(18, 18), whose result is ________. Equal deadlines make the method continue to the accession comparison.


L's accession number is ________, while N's is ________. The code evaluates Integer.compare(405, 401), which returns 1.


The final result is 1, so N comes before L. Matching the primary field did not settle the full comparison because the rule includes a secondary field.


c) List the distinct comparison groups from first to last, and determine whether L and P can be ordered relative to each other by this method.


M has the earliest deadline, so it forms the first group. Among the requests with the later deadline, N has the smallest accession number and forms the next group.


L and P match on both fields. Their deadline comparison returns zero, and their accession comparison also returns zero. Therefore, L.compareTo(P) and P.compareTo(L) both return zero.


The ordered groups are M, then N, then the tied group containing L and P. There are 3 distinct comparison groups. The method provides no before-or-after distinction between L and P; separate records can tie under the chosen comparison rule.

A library's Book class has a valid natural ordering. For two books, first.compareTo(second) returns -9. Which conclusion follows from this result alone?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A delivery application has a concrete Java class named Parcel. It implements Comparable with Parcel as the compared type and has no comparison implementation to inherit. Complete the description of the instance method that the class must provide. Use exact Java identifiers.


The method has the access modifier and the primitive return type . Its name is , and its single parameter has type .

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

An online leaderboard orders Player objects by higher score first, then lower penalty time first when scores tie. Scores are integer points; penalties are integer seconds. Its method is:


Java
public int compareTo(Player other) {
    int byScore = Integer.compare(other.score, this.score);
    if (byScore != 0) {
        return byScore;
    }
    return Integer.compare(this.penaltySeconds, other.penaltySeconds);
}


Player A has 82 points and a 9 s penalty. Player B has 95 points and a 14 s penalty. Player C has 82 points and a 5 s penalty. Player D has 82 points and a 9 s penalty.


Complete each cell with the exact integer returned by the method: -1, 0, or 1.

CallReturned integer
A.compareTo(B)
B.compareTo(A)
A.compareTo(C)
C.compareTo(A)
A.compareTo(D)
B.compareTo(C)

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice