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

The compare Method Contract: Return Values

Master the contract: return negative if first is less, zero if equal, positive if first is greater, and consistency requirements.

The compare Method Contract: Return Values

What you'll learn: You'll master exactly what numbers your Comparator's compare method must return and why consistency matters.

When you implement the Comparator interface, your compare method must follow a strict contract about its return values. This isn't optional—violating it breaks sorting algorithms and tree structures.

The Three Return Value Rules

Your compare(T o1, T o2) method must return:

  • A negative integer if o1 is less than o2
  • Zero if o1 is equal to o2
  • A positive integer if o1 is greater than o2

Notice it says "negative" and "positive"—not specifically -1 or +1. Returning -5 or +100 is perfectly valid. What matters is the sign.

The Consistency Requirement

Your comparator must be consistent with itself. If you compare the same two objects multiple times without changing them, you must get the same result. This seems obvious, but avoid using random numbers or timestamps in your comparison logic!

Think of It Like a Judge

Imagine a talent show judge comparing two performances. The judge must:

  • Give a thumbs down (negative) if the first is worse
  • Shrug (zero) if they're equally good
  • Give a thumbs up (positive) if the first is better

And most importantly: if the judge says Performance A beats Performance B, they can't later claim B beats A without something changing.

Key Takeaway: Your compare method must always return a negative number when the first argument is smaller, zero when equal, positive when greater—and it must be consistent across repeated comparisons of unchanged objects.