我在重写compareTo方法时遇到了问题。该程序模拟不同的员工类型,我让它完美地按员工类型排序,但不能让它按总工资进行第二次排序。一旦它按类名/employee类型排序,它就需要按grossPay排序,我可以通过一个帮助器方法获得它。代码如下:
public int compareTo(Object o) {
Employee other = (Employee) o;
if(other instanceof Salaried)
return -1;
else if(other instanceof Daily)
return 1;
else
return 0;
}我使用Collection.sort()和一个雇佣数组列表。当我打印输出时,我得到了一个很棒的按employee类型排序的列表,但是它应该按grossPay排序。
发布于 2012-06-17 10:13:37
compareTo必须返回与总订单一致的结果。否则,无法以任何方式保证排序结果。总顺序意味着如果为A<B,则为B>A;如果为A==B,则为B==A。换句话说,您可以切换this和other,并且结果是一致的。即使对于employee类型,您提供的代码也不能做到这一点。
如果compareTo与at total order不一致,sort可能会产生错误的答案,或者永远不会终止。
不清楚你的系统是有3种类型的员工,还是有2种类型的员工。让我们假设是2种:带薪的和每日的。然后我们需要处理这些可能性:
this other result
------------------------
salaried salaried equal
daily salaried <
salaried daily >
daily daily equal只有在我们确定了this和other在employee类型中是相等的之后,我们才会采用第二个排序关键字,即总工资。
因此,一种编码方法是:
// Assume this and o have type Daily or Salaried.
public int compareTo(Object o) {
if (this instanceof Daily && o instanceof Salaried) return -1;
if (this instanceof Salaried && o instanceof Daily) return +1;
// The employee types must be equal, so make decision on pay.
Employee e = (Employee)o;
return grossPay() < e.grossPay() ? -1 :
grossPay() > e.grossPay() ? +1 : 0;
}我假设这是在Employee中实现的。
最后,使用Comparator实现这种排序可能会更好。应该为“自然”排序顺序保留compareTo方法,例如作为主键的唯一id号的数字顺序。这种排序标准似乎并不“自然”。
发布于 2012-06-17 10:00:13
你可以在比较后比较grossPay,type.Assuming的grossPay是一个数字。
public int compareTo(Object o) {
Employee other = (Employee) o;
if(this instanceof Daily && other instanceof Salaried)
return -1;
else if(this instanceof Salaried && other instanceof Daily)
return 1;
else
return this.getGrossPay() - other.getGrossPay();
}https://stackoverflow.com/questions/11068350
复制相似问题