Java ProgramsCollectionsComparable Example

Comparable Example in Java

beginner·  Collections  ·  Comparator & Comparable

Problem

A class implements Comparable to declare its own natural ordering — a single compareTo() method that says, for any two instances, which one comes first.

Define a Student class that implements Comparable by score, and compare two instances directly.

Input
new Student("Ravi", 82).compareTo(new Student("Meera", 91))
Output
Ravi compared to Meera: -1

Java Program

Java
class Student implements Comparable<Student> { String name; int score; Student(String name, int score) { this.name = name; this.score = score; } public int compareTo(Student other) { return Integer.compare(this.score, other.score); // negative, zero, or positive — the sign is what matters } } public class ComparableExample { public static void main(String[] args) { Student a = new Student("Ravi", 82); Student b = new Student("Meera", 91); int result = a.compareTo(b); System.out.println(a.name + " compared to " + b.name + ": " + result); } }

Output

Ravi compared to Meera: -1

Core Logic

Overriding compareTo() to compare just the score field gives every Student a well-defined natural order, without needing a separate comparator object anywhere.

How It Works
  1. 1class Student implements Comparable<Student> commits the class to providing a compareTo(Student other) method.
  2. 2Integer.compare(this.score, other.score) returns a negative number, zero, or a positive number depending on whether this object's score is less than, equal to, or greater than the other's.
  3. 3Calling a.compareTo(b) directly runs that comparison between two specific Student instances.
  4. 4The returned int's sign is what matters — a negative result means a is 'less than' b under this ordering, not that the scores literally subtract to that value.
Ravi has a score of 82 and Meera has 91; since 82 < 91, a.compareTo(b) returns -1.
💡

Key Point: compareTo()'s contract only guarantees the sign of the result, not its exact magnitude — checking for negative/zero/positive is always correct, but relying on the specific number returned (like assuming it's the literal difference) isn't.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

Why: A single compareTo() call here just compares two int fields directly — its own cost would grow only if the fields being compared were themselves more expensive to compare, like strings or nested objects.

Key Concepts

Comparable<T>compareTo()Integer.compare()

Related Programs