Course contentsShow
← Java
Lesson 1313 of 2,87030. Comparable and ComparatorFree lesson

Return Values: Negative, Zero, Positive

Return negative if this object is less than the argument, zero if equal, and positive if greater than the argument.

Return Values: Negative, Zero, Positive

You'll learn the precise contract for compareTo return values that define object ordering in Java.

The Three-Way Contract

When you implement the compareTo method from Comparable<T>, you must return an integer that signals the ordering relationship between the current object (this) and the argument object:

  • Negative value (any negative int): this object is less than the argument
  • Zero: this object is equal to the argument
  • Positive value (any positive int): this object is greater than the argument

Notice it doesn't have to be specifically -1, 0, or 1—any negative or positive integer works.

Why This Matters

This return convention allows sorting algorithms to know how to order your objects. When a sorting method compares two elements, it calls compareTo and uses the sign of the result to decide their relative positions.

Simple Analogy

Think of a weighing scale with two sides. When you put two objects on it:

  • If the left side (this object) goes down → return negative (it's "heavier"/less in sort order)
  • If balanced → return zero (equal)
  • If the right side (argument) goes down → return positive (this is "lighter"/greater)

Practical Example Pattern

For comparing integers directly:

@Override
public int compareTo(Person other) {
    return this.age - other.age;  // Returns negative, zero, or positive
}

This works because subtraction naturally produces the correct sign for ordering.

Key Takeaway: The compareTo method must return a negative integer if this object is less than the argument, zero if equal, and a positive integer if greater—this three-way result enables Java's sorting and ordering mechanisms.