如何在Java中使用Comparable CompareTo on 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;
你需要使用的是字符串的compareTo()
方法。
return this.getName().compareTo(i.getName());
那应该做你想要的。
通常在实现Comparable
接口时,您将只聚合使用该类的其他Comparable
成员的结果。
下面是compareTo()
方法的一个非常典型的实现:
class Car implements Comparable { 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; } }
非常确定您的代码可以像这样编写:
public int compareTo(Emp other) { return this.getName().compareTo(other.getName()); }
Java String已经实现了Comparable。 所以你可以简单地把你的方法写成
public int compareTo(Emp emp) { return this.getName().compareTo(emp.getName()); }
(当然要确保添加适当的validation,例如空检查等)
同样在您的代码中,不要尝试使用’==’来比较字符串。 改为使用’equals’方法。 ‘==’仅比较字符串引用,而equals在语义上比较两个字符串。
你不需要把我施展给Emp,它已经是一个Emp:
public int compareTo(Emp i) { return getName().compareTo(i.getName()); }
不能
if (this.getName() == ((Emp ) i).getName())
是
if (this.getName().equals(i.getName()))