Search code examples
javajavadoccompareto

Javadoc comments - CompareTo?


My book asks me to write a Javadoc comment for a section of code. For the most part I understand how to do javadocs, but I do not understand what the program is doing.

"Write a Javadoc comment for the following method of a class Person. Assume that class Person has two String data fields lastName and firstName with the obvious meaning. Provide preconditions and postconditions if needed."

public int compareTo(Person per) {
    if (lastName.equals(per.lastName))
        return firstName.compareTo(per.firstName);
    else
        return lastName.compareTo(per.lastName);
}

/**
 * Method to return?
 *
 * @param compare the firstName lexicographically
 * @param compare the lastName  lexicographically
*/

I actually have no idea what this is doing. Is it returning a number? I looked at examples on

http://www.tutorialspoint.com/java/java_string_compareto.htm


Solution

  • Are you sure it doesn't look like this?

    Public int compareTo(Person per) {
        if(firstName.compareTo(per.firstName) != 0){
            return firstName.compareTo(per.firstName);
        }
        else{
            return lastName.compareTo(per.lastName);
        }
    
    }
    

    This code will order based off the lexicographically ordering of the first name, if they are the same it will then sort off the last name.

    Each compareTo method returns a -1, 0, or 1 depending on if the first string comes sooner in the ordering or not.