Java - 仅使用类似的接口比较两个字段

时间:2018-03-25 05:17:30

标签: java sorting comparable

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

1 个答案:

答案 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使用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;
}