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