Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the Comparable CompareTo on Strings in Java

I can use it to sort by emp id but I'm not sure if it is possible to compare strings. I get an error the operator is undefined for strings.

public int compareTo(Emp i) {
            if (this.getName() == ((Emp ) i).getName())
                return 0;
            else if ((this.getName()) > ((Emp ) i).getName())
                return 1;
            else
                return -1;
like image 739
Jack Avatar asked Sep 09 '25 16:09

Jack


2 Answers

What you need to use is the compareTo() method of Strings.

return this.getName().compareTo(i.getName());

That should do what you want.

Usually when implementing the Comparable interface, you will just combine the results of using other Comparable members of the class.

Below is a pretty typical implementation of a compareTo() method:

class Car implements Comparable<Car> {
    int year;
    String make, model;
    public int compareTo(Car other) {
        if (!this.make.equalsIgnoreCase(other.make))
            return this.make.compareTo(other.make);
        if (!this.model.equalsIgnoreCase(other.model))
            return this.model.compareTo(other.model);
        return this.year - other.year;
    }
}
like image 76
jjnguy Avatar answered Sep 12 '25 09:09

jjnguy


Pretty sure your code can just be written like this:

public int compareTo(Emp other)
{
    return this.getName().compareTo(other.getName());
}
like image 31
Sam Day Avatar answered Sep 12 '25 09:09

Sam Day