我尝试仅使用Comparable接口比较两个字段(字符串和整数)。这是我第一次使用它,我不知道在哪里放第二个字段来比较值。
public int compareTo(Object o) throws ClassCastException
{
int count = 0;
int compareName = this.lastName.compareTo(((SalePerson) o).getLastName());
int compareSales = Integer.compare(this.totalSales, ((SalePerson) o).getTotalSales());
if(!(o instanceof SalePerson))
{
throw new ClassCastException("A SalePerson object expected.");
}
if((this.totalSales < ((SalePerson) o).getTotalSales()))
{
count = -1;
}
else if((this.totalSales > ((SalePerson) o).getTotalSales()))
{
count = 1;
}
return count;
}
答案 0 :(得分:2)
如果要实现Comparable
接口,那么抛出ClassCastException
是不必要的,因为o
必须是SalePerson
,否则会出现编译错误。
你可以这样做:
public class SalePerson implements Comparable<SalePerson>{
@Override
public int compareTo(SalePerson o) {
int totalSalesCompare = Integer.compare(this.totalSales, o.getTotalSales());
return totalSalesCompare == 0 ? this.lastName.compareTo(o.getLastName())
: totalSalesCompare;
}
}
此外,建议compareTo
使用equals
和hashCode
:
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof SalePerson)) {
return false;
}
return Integer.compare(Integer.compare(this.totalSales, o.getTotalSales())) == 0
&& this.lastName.equals(o.getLastName());
}
@Override
public int hashCode() {
return this.lastName.hashCode() * 31 + this.totalSales;
}