Java Comparable Interface - Sorting Custom Objects Made Easy

Learn how to use Java's Comparable interface to define custom sorting for your objects. By implementing Comparable, you can specify sorting logic for complex types, allowing seamless ordering in Java Collections. Discover examples and best practices to make your custom objects sortable and enhance the efficiency of your Java applications.



Java - How to Use Comparable

Java Comparable Interface

The Comparable interface is an essential tool in Java, used by Java Collections to compare and sort custom objects. By implementing this interface, you can define how your custom objects should be sorted, similar to how wrapper classes and strings are sorted using the built-in sorting methods in Collections.

Using the Comparable interface, we can make objects sortable.

Comparable Interface Methods

The compareTo() Method

The compareTo() method compares the passed object for ordering. The method signature is:

Syntax

int compareTo(Object obj)

The compareTo() method returns:

  • 0 if the objects are equal
  • A positive value if the current object is greater than the passed object (obj)
  • A negative value if the current object is less than the passed object

By overriding compareTo(), you can customize how objects are ordered. For example, to sort in reverse order, you can implement a comparison method that reverses the result of a comparison.

The equals() Method

The equals() method checks if the current object is equal to the passed object:

Syntax

boolean equals(Object obj)

The equals() method returns true if both objects are Comparator objects and use the same ordering; otherwise, it returns false.

Note that overriding equals() is not necessary in most cases.

Comparable Interface to Sort Custom Objects

In the following example, we will use the Comparable interface to sort custom Dog objects based on their names.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Dog implements Comparable {
private String name;
private int age;

Dog(String n, int a) {
    name = n;
    age = a;
}

public String getDogName() {
    return name;
}

public int getDogAge() {
    return age;
}

// Overriding the compareTo method
public int compareTo(Dog d) {
    return this.name.compareTo(d.name); // Alphabetical order by name
}

@Override
public String toString() {
    return this.name + "," + this.age;
}
}

public class ComparableDemo {
public static void main(String[] args) {
    List list = new ArrayList<>();

    list.add(new Dog("Shaggy", 3));
    list.add(new Dog("Lacy", 2));
    list.add(new Dog("Roger", 10));
    list.add(new Dog("Tommy", 4));
    list.add(new Dog("Tammy", 1));

    Collections.sort(list); // Sorts by name
    System.out.println("Sorted by name:");
    System.out.println(list);
}
}
Output

Sorted by name:
[Lacy,2, Roger,10, Shaggy,3, Tammy,1, Tommy,4]

Comparable Interface to Sort in Reverse Order

In this example, we will sort the Dog objects in reverse alphabetical order using the Collections.reverseOrder() method.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Dog implements Comparable {
private String name;
private int age;

Dog(String n, int a) {
    name = n;
    age = a;
}

public String getDogName() {
    return name;
}

public int getDogAge() {
    return age;
}

// Overriding the compareTo method
public int compareTo(Dog d) {
    return this.name.compareTo(d.name); // Alphabetical order by name
}

@Override
public String toString() {
    return this.name + "," + this.age;
}
}

public class ComparableDemo {
public static void main(String[] args) {
    List list = new ArrayList<>();

    list.add(new Dog("Shaggy", 3));
    list.add(new Dog("Lacy", 2));
    list.add(new Dog("Roger", 10));
    list.add(new Dog("Tommy", 4));
    list.add(new Dog("Tammy", 1));

    Collections.sort(list, Collections.reverseOrder()); // Sorts in reverse order
    System.out.println("Sorted by name in reverse order:");
    System.out.println(list);
}
}
Output

Sorted by name in reverse order:
[Tommy,4, Tammy,1, Shaggy,3, Roger,10, Lacy,2]

Comparable Interface to Sort by Age

In this example, we will modify the comparison logic to sort the Dog objects based on their age.

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Dog implements Comparable {
private String name;
private int age;

Dog(String n, int a) {
    name = n;
    age = a;
}

public String getDogName() {
    return name;
}

public int getDogAge() {
    return age;
}

// Overriding the compareTo method
public int compareTo(Dog d) {
    return this.age - d.age; // Sort by age
}

@Override
public String toString() {
    return this.name + "," + this.age;
}
}

public class ComparableDemo {
public static void main(String[] args) {
    List list = new ArrayList<>();

    list.add(new Dog("Shaggy", 3));
    list.add(new Dog("Lacy", 2));
    list.add(new Dog("Roger", 10));
    list.add(new Dog("Tommy", 4));
    list.add(new Dog("Tammy", 1));

    Collections.sort(list); // Sorts by age
    System.out.println("Sorted by age:");
    System.out.println(list);
}
}
Output

Sorted by age:
[Tammy,1, Lacy,2, Shaggy,3, Tommy,4, Roger,10]

Conclusion

The Comparable interface allows for seamless sorting of custom objects in Java without compromising backward compatibility. By implementing compareTo(), we can define custom sorting rules for any object. The examples above demonstrate sorting by name in both alphabetical and reverse order, as well as sorting by age.