我可以使用它来按 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;
最佳答案
你需要用到的是Strings的compareTo()
方法。
return this.getName().compareTo(i.getName());
这应该可以满足您的需求。
通常在实现Comparable
接口(interface)时,只是将使用类的其他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;
}
}
关于java - 如何在 Java 中的字符串上使用 Comparable CompareTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3748805/