简体   繁体   中英

Java - Compare two fields using only comparable interface

I'm trying to compare two fields (string and integer) using only the Comparable interface. It was my first time using this and I've no idea where to put the second field to compare the values.

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

If you want to implement Comparable interface, it is unecassary to throw ClassCastException since o has to be SalePerson , otherwise you will get a compile error.

You can do it this way:

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;

    }
}

Also, the compareTo is suggested to work with equals and 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM