如何在Java中使用Comparable CompareTo on Strings

Jac*_*ack 22 java compareto comparable

我可以使用它按emp id排序,但我不确定是否可以比较字符串.我得到一个错误,操作符未定义为字符串.

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;
Run Code Online (Sandbox Code Playgroud)

jjn*_*guy 46

你需要使用的是compareTo()字符串的方法.

return this.getName().compareTo(i.getName());
Run Code Online (Sandbox Code Playgroud)

那应该做你想要的.

通常在实现Comparable接口时,您只需聚合使用Comparable该类的其他成员的结果.

下面是一个非常典型的compareTo()方法实现:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*Day 7

非常确定您的代码可以像这样编写:

public int compareTo(Emp other)
{
    return this.getName().compareTo(other.getName());
}
Run Code Online (Sandbox Code Playgroud)


Gop*_*opi 5

Java String已经实现了Comparable。因此,您只需将您的方法编写为

public int compareTo(Emp emp) {
   return this.getName().compareTo(emp.getName());
}
Run Code Online (Sandbox Code Playgroud)

(当然,请确保您添加了适当的验证,例如null检查等)

同样在您的代码中,请勿尝试使用'=='比较字符串。请改用“等于”方法。'=='仅比较字符串引用,而equals在语义上比较两个字符串。