compareTo() and Comparable
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 44 of 87.
The Comparable interface allows objects to define their natural ordering. By implementing this interface, your class can be sorted automatically using methods like Collections.sort() or stored in sorted collections like TreeSet.
The interface requires you to implement a single method: compareTo(). This method compares the current object with another object and returns an integer indicating their relative order:
- Negative value: this object comes before the other
- Zero: both objects are equal
- Positive value: this object comes after the other
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Person other) {
return this.age - other.age; // Sort by age ascending
}
}Once implemented, sorting becomes straightforward:
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
Collections.sort(people); // Now sorted by age: Bob, AliceFor comparing strings or other Comparable fields, you can delegate to their compareTo() method instead of using subtraction: return this.name.compareTo(other.name);. This approach is safer and handles edge cases properly.
Challenge
EasyLet's build a movie ranking system that uses the Comparable interface to sort movies by their ratings. You'll create a Movie class that knows how to compare itself with other movies, enabling automatic sorting from highest to lowest rated.
You'll organize your code across two files:
Movie.java: Create a class representing a movie that can be compared with other movies. A Movie has three private fields:title(String),director(String), andrating(double, from 0.0 to 10.0). Include a constructor to initialize all fields and getter methods for each.Make your Movie class implement
Comparable<Movie>and override thecompareTo()method. Movies should be sorted by rating in descending order (highest rated first). When comparing doubles, useDouble.compare()for safe comparison—remember to reverse the order for descending sort!Override
toString()to return:[title] by [director] - Rating: [rating]Main.java: Bring your Movie class to life by creating a list of movies and sorting them. You'll receive input for three movies, each on a separate line in the format:title,director,ratingParse each line to create Movie objects, add them to an
ArrayList, then useCollections.sort()to sort the list. Thanks to yourComparableimplementation, the movies will automatically arrange themselves by rating!After sorting, print each movie on its own line using the
toString()format. The highest-rated movie should appear first.
You will receive three lines of input, each containing movie data in the format: title,director,rating
For example, an input line might look like: Inception,Christopher Nolan,8.8
Remember to import java.util.ArrayList, java.util.Collections, and java.util.Scanner in your Main file. Notice how implementing Comparable lets you sort your custom objects with a single method call—no extra comparator needed!
Cheat sheet
The Comparable interface allows objects to define their natural ordering for automatic sorting.
Implement the compareTo() method which returns:
- Negative value: this object comes before the other
- Zero: both objects are equal
- Positive value: this object comes after the other
public class Person implements Comparable<Person> {
private int age;
@Override
public int compareTo(Person other) {
return this.age - other.age; // Sort by age ascending
}
}Sort objects using Collections.sort():
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
Collections.sort(people); // Sorted by ageFor comparing strings, delegate to their compareTo() method:
return this.name.compareTo(other.name);For comparing doubles safely, use Double.compare():
return Double.compare(this.rating, other.rating); // Ascending
return Double.compare(other.rating, this.rating); // DescendingTry it yourself
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Read three lines of movie data
String line1 = scanner.nextLine();
String line2 = scanner.nextLine();
String line3 = scanner.nextLine();
// TODO: Create an ArrayList to store Movie objects
// TODO: Parse each line (format: title,director,rating)
// Hint: Use split(",") to separate the parts
// Hint: Use Double.parseDouble() for the rating
// TODO: Create Movie objects and add them to the list
// TODO: Sort the list using Collections.sort()
// TODO: Print each movie (one per line)
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System