2012-06-17 25 views
0

我遇到了一个compareTo方法的问题。该程序模拟不同的员工类型,并且我按照员工类型进行了完美排序,但无法按总薪酬进行二次排序。一旦按照类名称/员工类型排序,它就需要按照grossPay进行排序,我可以通过辅助方法获取这些数据。以下是代码:CompareTo Overide Sort

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

我正在使用Collectionssort()与employess的arraylist。当我打印出来的时候,我根据员工类型得到了一个很好的排序清单,但是应该按照grossPay排序。

+0

你可能想看看[http://stackoverflow.com/questions/369512/best-way-to-compare-objects-by-multiple-fields](http://stackoverflow.com/questions/369512 /最好的路到比较对象按多字段)。它(据我了解)几乎可以回答你的问题。 – purtip31

回答

3

您可以比较类型比较后的grossPay。假设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(); 
} 
+2

关闭,但由于溢出的可能性,您不应该使用整数减法来实现'compareTo'。如果'getGrossPay()'已经返回了一个'Integer'值,那么你可以使用Integer.compareTo,但是对于原语,坚持'<' and '>'。在Java 7中,有一个静态方法'Integer.compare(int,int)'。 –

+0

不幸的是,这并不确定。如果'这是薪水,另一个是薪水,这将返回'-1'。如果交换两个操作数,它将再次返回'-1'。所以比较与总订单不一致。这种排序可能会产生错误的答案或永不终止。 – Gene

+0

@Gene我编辑了我的答案。 – plucury

6

compareTo必须返回的结果总顺序一致。否则,排序结果不能以任何方式保证。总订单意味着如果A<B,那么B>AA==B,然后B==A。换句话说,您可以切换thisother,结果是一致的。即使对于员工类型,您所提供的代码也不会这样做。

如果compareTo与总订单不一致,sort可能会产生错误答案或永不终止。

目前还不清楚您的系统是否有3种类型的员工或2.我们假设这是2:薪水和每日。然后,我们需要通过possiblities工作:

this  other result 
------------------------ 
salaried salaried equal 
daily salaried < 
salaried daily > 
daily daily equal 

只有当我们已经建立,这和其他的员工类型等于做我们把次要排序键,这是工资总额。

因此,要编写一个方法是:

// 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方法应保留为“自然”排序顺序,例如充当主键的唯一标识号的数字顺序。这种排序标准似乎并不“自然”。

+0

“比较器”的+1。 – Genzer