Natural order with Comparable
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}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:
32and1both just mean "after". String.compareToreturns the gap between the first different characters:'a'(97) minus'A'(65) is 32.Integer.compare(x, y)gives the same answer ascompareTofor twointvalues.
Example 2 · Mistake: sorting objects that cannot be compared
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); }}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 errorWhat this code does
Collections.sort(list)asks forT extends Comparable<? super T>: the bounded type from the Generics module.Studentdoes not implementComparable, 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 aComparator, 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.
Example 3 · Student implements Comparable: sort by marks
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()); }}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 comparesthisstudent withotherand returns negative, zero or positive.Integer.compare(this.marks, other.marks)gives the right sign for us. NowCollections.sort,Collections.minandCollections.maxall work, because they all use this natural order.
compareTo answers with a number, and only its sign matters:
- Return a negative number if
thiscomes beforeother. - Return zero if both have the same place.
- Return a positive number if
thiscomes afterother. String,Integer,Double,Characterand many more already implement it. That is their natural order.
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
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)); }}[Rohit 103, Kohli 76, Gill 48, Pant 12] [Rahul 61, Jadeja 35]
What this code does
- To sort from high to low, compare
otherwiththisinstead ofthiswithother. The sign flips, so the order flips. - The natural order also works for arrays:
Arrays.sorton aPlayer[]uses the samecompareTo.
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.
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
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)); }}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 noComparablebound, so this compiles. At run time it casts eachBooktoComparable, and the cast fails.- The fix is the same as before:
class Book implements Comparable<Book>with acompareTo, for examplereturn this.title.compareTo(other.title);.
Example 6 · Consistent with equals: add a tie-breaker
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)); }}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,
compareTowould return 0 and call them "the same", whileequalssays they are not. The roll-number tie-breaker makescompareToreturn 0 only whenequalsis true. - Now ties have a fixed order (roll 7 before roll 12), and
binarySearchfinds exactly Priya. Sorted sets and maps also treatcompareTo == 0as 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
compareToreturns 0 exactly whenequalsistrue. 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.
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))); }}[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