How do I write a compareTo method which compares objects?

Jeremy B picture Jeremy B · Apr 4, 2012 · Viewed 157.7k times · Source

I am learning about arrays, and basically I have an array that collects a last name, first name, and score.

I need to write a compareTo method that will compare the last name and then the first name so the list could be sorted alphabetically starting with the last names, and then if two people have the same last name then it will sort the first name.

I'm confused, because all of the information in my book is comparing numbers, not objects and Strings.

Here is what I have coded so far. I know it's wrong but it at least explains what I think I'm doing:

public int compare(Object obj) // creating a method to compare 
{   
    Student s = (Student) obj; // creating a student object

    // I guess here I'm telling it to compare the last names?
    int studentCompare = this.lastName.compareTo(s.getLastName()); 

    if (studentCompare != 0)
        return studentCompare;
    else 
    {
        if (this.getLastName() < s.getLastName())
            return - 1;

        if (this.getLastName() > s.getLastName())
            return 1;
    }
    return 0;
}

I know the < and > symbols are wrong, but like I said my book only shows you how to use the compareTo.

Answer

Eugene Retunsky picture Eugene Retunsky · Apr 4, 2012

This is the right way to compare strings:

int studentCompare = this.lastName.compareTo(s.getLastName()); 

This won't even compile:

if (this.getLastName() < s.getLastName())

Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead.

So to compare fist/last name order you need:

int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
    d = getLastName().compareTo(s.getLastName());
return d;