Skip to lesson

Natural order with Comparable

Sorting a list of numbers works at once, but sorting a list of Student objects fails. Java cannot guess which student comes first.

Why sorting your own objects fails

Natural order is the default order of a class's objects, such as numbers from small to large or Strings from A to Z. Java uses it whenever you sort without giving a comparator.

Collections.sort already sorts a List<String>, but for a List<Student> Java does not know what "smaller" means: by marks, by name or by roll number? Only you can decide.

Example 1 · compareTo on String and Integer

CompareToDemo.javaJava
public class CompareToDemo {    public static void main(String[] args) {        System.out.println("Laptop vs Mouse: " + "Laptop".compareTo("Mouse"));        System.out.println("Mouse vs Laptop: " + "Mouse".compareTo("Laptop"));        System.out.println("Mouse vs Mouse:  " + "Mouse".compareTo("Mouse"));        System.out.println("laptop vs Laptop:  " + "laptop".compareTo("Laptop"));
        Integer a = 45;        Integer b = 90;        System.out.println("45 vs 90: " + a.compareTo(b));        System.out.println("90 vs 45: " + b.compareTo(a));        System.out.println("Integer.compare(7, 7): " + Integer.compare(7, 7));    }}
Output
Laptop vs Mouse: -1
Mouse vs Laptop: 1
Mouse vs Mouse:  0
laptop vs Laptop:  32
45 vs 90: -1
90 vs 45: 1
Integer.compare(7, 7): 0

What this code does

  • Negative means "this comes first", zero means "same place", positive means "this comes after". Only the sign matters: 32 and 1 both just mean "after".
  • String.compareTo returns the gap between the first different characters: 'a' (97) minus 'A' (65) is 32. Integer.compare(x, y) gives the same answer as compareTo for two int values.

Example 2 · Mistake: sorting objects that cannot be compared

SortStudentsDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
class Student {    private String name;    private int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }
    @Override    public String toString() {        return name + "(" + marks + ")";    }}
public class SortStudentsDemo {    public static void main(String[] args) {        List<Student> students = new ArrayList<>();        students.add(new Student("Aarav", 85));        students.add(new Student("Priya", 92));        students.add(new Student("Rohan", 78));        Collections.sort(students);        System.out.println(students);    }}
Sample compiler output
SortStudentsDemo.java:26: error: no suitable method found for sort(List<Student>)
        Collections.sort(students);
                   ^
    method Collections.<T#1>sort(List<T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: Student
        upper bounds: Comparable<? super T#1>)
    method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))
  where T#1,T#2 are type-variables:
    T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
    T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
1 error

What this code does

  • Collections.sort(list) asks for T extends Comparable<? super T>: the bounded type from the Generics module. Student does not implement Comparable, so the compiler refuses.
  • The message is long, but the key line is upper bounds: Comparable<? super T#1>. It means: "your class must be Comparable". The second method mentioned needs a Comparator, the topic of the next lesson.

So Collections.sort(students) is a compile error until Student tells Java how to compare two students. You saw the reason in the Generics module: sort is declared with the bound <T extends Comparable<? super T>>.

The Comparable interface

Comparable<T> is an interface in java.lang with one method, int compareTo(T other). A class that implements it defines its natural order: compareTo returns a negative number, zero or a positive number when this comes before, ties with or comes after other.

Comparable<T> is in java.lang, so it needs no import. It has one method, int compareTo(T other), which compares this object with other.

What compareTo returns. "Laptop".compareTo("Mouse") is -1, a negative number, so the order stays. "Mouse".compareTo("Mouse") is 0, a tie, so the order stays. "Mouse".compareTo("Laptop") is 1, a positive number, so the two items swap and Laptop comes first.

Example 3 · Student implements Comparable: sort by marks

SortStudentsDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
class Student implements Comparable<Student> {    private String name;    private int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }
    String getName() {        return name;    }
    @Override    public int compareTo(Student other) {        return Integer.compare(this.marks, other.marks);   // lower marks first    }
    @Override    public String toString() {        return name + "(" + marks + ")";    }}
public class SortStudentsDemo {    public static void main(String[] args) {        List<Student> students = new ArrayList<>();        students.add(new Student("Aarav", 85));        students.add(new Student("Priya", 92));        students.add(new Student("Rohan", 78));        students.add(new Student("Kavya", 88));
        Collections.sort(students);        System.out.println("Sorted: " + students);        System.out.println("Lowest: " + Collections.min(students).getName());        System.out.println("Topper: " + Collections.max(students).getName());    }}
Output
Sorted: [Rohan(78), Aarav(85), Kavya(88), Priya(92)]
Lowest: Rohan
Topper: Priya

What this code does

  • implements Comparable<Student> promises one method: public int compareTo(Student other). It compares this student with other and returns negative, zero or positive.
  • Integer.compare(this.marks, other.marks) gives the right sign for us. Now Collections.sort, Collections.min and Collections.max all work, because they all use this natural order.

compareTo answers with a number, and only its sign matters:

  • Return a negative number if this comes before other.
  • Return zero if both have the same place.
  • Return a positive number if this comes after other.
  • String, Integer, Double, Character and many more already implement it. That is their natural order.
Only the sign matters. Never test compareTo(...) == -1; test < 0, == 0 or > 0.

Writing compareTo step by step

Pick the field that decides the order. For an int field, return Integer.compare(this.marks, other.marks); for a double, use Double.compare; for a String, call this.name.compareTo(other.name).

Example 4 · Highest first: swap the two values

TopScorersDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;
class Player implements Comparable<Player> {    private String name;    private int runs;
    Player(String name, int runs) {        this.name = name;        this.runs = runs;    }
    @Override    public int compareTo(Player other) {        return Integer.compare(other.runs, this.runs);   // more runs first    }
    @Override    public String toString() {        return name + " " + runs;    }}
public class TopScorersDemo {    public static void main(String[] args) {        List<Player> innings = new ArrayList<>();        innings.add(new Player("Gill", 48));        innings.add(new Player("Rohit", 103));        innings.add(new Player("Kohli", 76));        innings.add(new Player("Pant", 12));        Collections.sort(innings);        System.out.println(innings);
        Player[] squad = {new Player("Jadeja", 35), new Player("Rahul", 61)};        Arrays.sort(squad);        System.out.println(Arrays.toString(squad));    }}
Output
[Rohit 103, Kohli 76, Gill 48, Pant 12]
[Rahul 61, Jadeja 35]

What this code does

  • To sort from high to low, compare other with this instead of this with other. The sign flips, so the order flips.
  • The natural order also works for arrays: Arrays.sort on a Player[] uses the same compareTo.

To reverse the order (highest first), swap the two values: Integer.compare(other.marks, this.marks). If two objects tie on the first field, compare a second field, and return that result only when the first comparison gave 0.

The method must be public, because interface methods are public. Avoid return this.marks - other.marks;: subtraction can overflow and give the wrong sign.

Predict the output

Which product comes first?

Read each program and pick what it prints.

Round 1 of 3

Sort by price, cheapest first.

import java.util.*;
class Product implements Comparable<Product> {
String name;
int price;
Product(String name, int price) {
this.name = name;
this.price = price;
}
public int compareTo(Product other) {
return Integer.compare(this.price, other.price);
}
}
public class FirstByPrice {
public static void main(String[] args) {
List<Product> list = new ArrayList<>();
list.add(new Product("Laptop", 55000));
list.add(new Product("Mouse", 700));
list.add(new Product("Monitor", 11000));
Collections.sort(list);
System.out.println(list.get(0).name);
}
}

The contract: rules compareTo must follow

The compareTo contract is the set of rules every compareTo must follow: negative when this comes first, zero for a tie, positive when this comes after, opposite signs when the two objects are swapped, and the same answer every time.

Sorting code trusts your compareTo. If it breaks these rules, sorting and searching give wrong answers, or even throw an exception.

Example 5 · Trap: Arrays.sort compiles, then crashes

SortBooksDemo.javaJava
import java.util.Arrays;
class Book {    private String title;
    Book(String title) {        this.title = title;    }
    @Override    public String toString() {        return title;    }}
public class SortBooksDemo {    public static void main(String[] args) {        Book[] shelf = {new Book("Wings of Fire"), new Book("Godaan"), new Book("Malgudi Days")};        Arrays.sort(shelf);        System.out.println(Arrays.toString(shelf));    }}
Sample output
Exception in thread "main" java.lang.ClassCastException: class Book cannot be cast to class java.lang.Comparable (Book is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')
	at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
	at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
	at java.base/java.util.Arrays.sort(Arrays.java:1041)
	at SortBooksDemo.main(SortBooksDemo.java:19)

What this code does

  • Arrays.sort(Object[]) has no Comparable bound, so this compiles. At run time it casts each Book to Comparable, and the cast fails.
  • The fix is the same as before: class Book implements Comparable<Book> with a compareTo, for example return this.title.compareTo(other.title);.

Example 6 · Consistent with equals: add a tie-breaker

TieBreakDemo.javaJava
import java.util.ArrayList;import java.util.Collections;import java.util.List;
class Student implements Comparable<Student> {    private int roll;    private String name;    private int marks;
    Student(int roll, String name, int marks) {        this.roll = roll;        this.name = name;        this.marks = marks;    }
    @Override    public boolean equals(Object o) {        if (this == o) {            return true;        }        if (!(o instanceof Student)) {            return false;        }        Student s = (Student) o;        return roll == s.roll;    }
    @Override    public int hashCode() {        return Integer.hashCode(roll);    }
    @Override    public int compareTo(Student other) {        int byMarks = Integer.compare(this.marks, other.marks);        if (byMarks != 0) {            return byMarks;        }        return Integer.compare(this.roll, other.roll);   // tie-breaker    }
    @Override    public String toString() {        return roll + "-" + name + "(" + marks + ")";    }}
public class TieBreakDemo {    public static void main(String[] args) {        Student aarav = new Student(12, "Aarav", 85);        Student priya = new Student(7, "Priya", 85);        System.out.println("equals:    " + aarav.equals(priya));        System.out.println("compareTo: " + aarav.compareTo(priya));
        List<Student> list = new ArrayList<>();        list.add(aarav);        list.add(new Student(3, "Rohan", 72));        list.add(priya);        Collections.sort(list);        System.out.println(list);
        Student lookFor = new Student(7, "Priya", 85);        System.out.println("Priya found at " + Collections.binarySearch(list, lookFor));    }}
Output
equals:    false
compareTo: 1
[3-Rohan(72), 7-Priya(85), 12-Aarav(85)]
Priya found at 1

What this code does

  • Aarav and Priya have the same marks but are different students. With marks alone, compareTo would return 0 and call them "the same", while equals says they are not. The roll-number tie-breaker makes compareTo return 0 only when equals is true.
  • Now ties have a fixed order (roll 7 before roll 12), and binarySearch finds exactly Priya. Sorted sets and maps also treat compareTo == 0 as a duplicate, which the Sets module shows.

The rules:

  • Opposite signs: if a.compareTo(b) is negative, b.compareTo(a) must be positive, and zero both ways.
  • Chains hold: if a comes before b and b before c, then a comes before c.
  • Same result every time for the same two objects.
  • Recommended: consistent with equals, so compareTo returns 0 exactly when equals is true. A tie-breaker field, such as the roll number, usually does it.

Where the natural order is used

Once a class is Comparable, many tools work with it for free: Collections.sort(list) and list.sort(null), Arrays.sort(array), Collections.max and Collections.min, and Collections.binarySearch. Later, TreeSet, TreeMap and PriorityQueue use it too.

NaturalOrderTools.javaJava
import java.util.*;
public class NaturalOrderTools {    public static void main(String[] args) {        List<String> names = new ArrayList<>(List.of("Ravi", "Asha", "Meena"));        Collections.sort(names);        System.out.println(names);        System.out.println(Collections.max(names) + " " + Collections.min(names));        System.out.println(Collections.binarySearch(names, "Meena"));        System.out.println(new TreeSet<>(List.of(72, 35, 88)));    }}
Output
[Asha, Meena, Ravi]
Ravi Asha
1
[35, 72, 88]

A class has only one natural order. When you need another order, such as by name on one screen and by marks on another, you use a Comparator. That is the next lesson.

Next step

Check your understanding

12 quick questions