Implementing custom compareTo

Anjan Baradwaj picture Anjan Baradwaj · Sep 12, 2013 · Viewed 47.9k times · Source
@Override
public int compareTo(Object t) 
{
    if(t instanceof Student)
    {
        Student s = (Student)t;
        return (this.name.compareTo(s.name));
    }
    else
        return -1;
}

This is my compareTo method implementation for comparing two Student objects based on their name. Is it possible to compare two such objects based on multiple fields i.e., both name and age?

Answer

Bohemian picture Bohemian · Sep 12, 2013

Yes, but first you should type the Comparable interface you're implementing. Here's what it should look like:

public class Student implements Comparable<Student> {
    private int age;
    private String name;
    @Override
    public int compareTo(Student s) {
        if (name.equals(s.name))
            return age - s.age;
        return name.compareTo(s.name));
    }
}

Notice how with the typed interface Comparable<Student>, instead of the raw type Comparable, there's no need to cast.