如何在 Java 中对字符串使用 Comparable CompareTo
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3748805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use the Comparable CompareTo on Strings in Java
提问by Hyman
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.
我可以用它来按 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;
回答by jjnguy
What you need to use is the compareTo()method of Strings.
您需要使用的是compareTo()Strings的方法。
return this.getName().compareTo(i.getName());
That should do what you want.
那应该做你想做的。
Usually when implementing the Comparableinterface, you will just aggregate the results of using other Comparablemembers of the class.
通常在实现Comparable接口时,您只会聚合使用Comparable类其他成员的结果。
Below is a pretty typical implementation of a compareTo()method:
下面是一个非常典型的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;
}
}
回答by zengr
Shouldn't
不应该
if (this.getName() == ((Emp ) i).getName())
if (this.getName() == ((Emp ) i).getName())
be
是
if (this.getName().equals(i.getName()))
if (this.getName().equals(i.getName()))
回答by Thomas Mueller
You don't need to cast i to Emp, it's already an Emp:
你不需要将 i 转换为 Emp,它已经是一个 Emp:
public int compareTo(Emp i) {
return getName().compareTo(i.getName());
}
回答by Gopi
Java Stringalready implements Comparable. So you could simply write your method as
Java String已经实现了 Comparable。所以你可以简单地把你的方法写成
public int compareTo(Emp emp) {
return this.getName().compareTo(emp.getName());
}
(ofcourse make sure you add proper validations such as null checks etc)
(当然,请确保添加适当的验证,例如空检查等)
Also in your code, do not try to compare Strings using '=='. Use 'equals' method instead. '==' only compare string references while equalssemantically compares two strings.
同样在您的代码中,不要尝试使用“==”来比较字符串。改用'equals'方法。'==' 只比较字符串引用,而等于语义比较两个字符串。
回答by Sam Day
Pretty sure your code can just be written like this:
很确定你的代码可以这样写:
public int compareTo(Emp other)
{
return this.getName().compareTo(other.getName());
}

