本文介绍了如何在Java中使用Comparable CompareTo on Strings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用它按emp id排序,但我不确定是否可以比较字符串。我得到一个错误,操作符未定义为字符串。
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;
推荐答案
您需要使用的是 compareTo()
字符串的方法。
What you need to use is the compareTo()
method of Strings.
return this.getName().compareTo(i.getName());
这应该做你想要的。
通常在实现 Comparable
界面时,您只会汇总使用该类其他 Comparable
成员的结果。
Usually when implementing the Comparable
interface, you will just aggregate the results of using other Comparable
members of the class.
下面是一个非常典型的 compareTo()
方法的实现:
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;
}
}
这篇关于如何在Java中使用Comparable CompareTo on Strings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!