Java - 仅使用可比接口比较两个字段

Java - Compare two fields using only comparable interface

我正在尝试仅使用 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;
}

如果要实现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 建议与 equalshashCode 一起使用:

@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;
}