Menu
Coddy logo textTech

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, Alice

For 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 icon

Challenge

Easy

Let'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), and rating (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 the compareTo() method. Movies should be sorted by rating in descending order (highest rated first). When comparing doubles, use Double.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,rating

    Parse each line to create Movie objects, add them to an ArrayList, then use Collections.sort() to sort the list. Thanks to your Comparable implementation, 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 age

For 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);  // Descending

Try 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)
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming