0

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;
}
7
  • Which two fields? Commented Mar 25, 2018 at 5:19
  • 1
    lastname and totalsales Commented Mar 25, 2018 at 5:19
  • so last names should equal and comparison based on total sales? Commented Mar 25, 2018 at 5:20
  • its like sorting both lastname and totalsales in ascending order Commented Mar 25, 2018 at 5:21
  • In which order do you want to compare? I mean which field should be compared first? Commented Mar 25, 2018 at 5:22

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.