Search code examples
javacompareto

Java Programming: How to use compareTo when comparing the names of the candidates in a text document


This method is used to compare the names of two candidates. Returns 0 if the name of this candidate is the same as the name of otherCan; returns < 0 if the name of this candidate is less then the name of otherCan; returns > 0 if the name of this candidate is greater than the name of otherCan.

@Override
    public int compareTo(Candidate otherCan) {
        if(name = otherCan){
        return this.name.compareToIgnoreCase(otherCan.getName());
    } else if(name < otherCan){
            return name < 0
        } else if(name > otherCan){
        return name > 0
        }
}

How do I compare them and what does return > 0 and < 0 mean?


Solution

  • There are many problems with this example.

        public int compareTo(Candidate otherCan) {
            if(name = otherCan){
    

    As I pointed out in a comment, this must be ==; otherwise, you're assigning the value of otherCan to name.

            return this.name.compareToIgnoreCase(otherCan.getName());
    

    If name == otherCan is true, then this call will always return 0.

        } else if(name < otherCan){
                return name < 0
    

    This line shouldn't compile because it's trying to return a boolean in a method that return an int.

            } else if(name > otherCan){
            return name > 0
    

    Same as the previous note; this shouldn't compile. } }

    This entire method is unnecessary. Just calling name.compareToIgnoreCase(otherCan.getName()) is enough, as it will return 0 if the strings are equal, a negative number (not necessarily -1) if the first string comes before the second in sorted order, and a positive number if the second string should come first.