有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

参数按日期排序。比较器。JAVA

下一个片段取自thisjava教程,它将第二个参数对象与第一个参数对象进行比较,而不是相反。 *方法hireDate()返回一个日期对象,表示该特定员工的雇用日期

import java.util.*;
public class EmpSort {
    static final Comparator<Employee> SENIORITY_ORDER = 
                                        new Comparator<Employee>() {
            public int compare(Employee e1, Employee e2) {
                return e2.hireDate().compareTo(e1.hireDate());
            }
    };

以下是java教程的说明:

Note that the Comparator passes the hire date of its second argument to its first rather than vice versa. The reason is that the employee who was hired most recently is the least senior; sorting in the order of hire date would put the list in reverse seniority order.

我仍然不明白为什么在compareTo中反转e1和e2可以解决这个问题

有进一步的澄清吗

提前谢谢


共 (3) 个答案

  1. # 1 楼答案

    日期的自然顺序(如compareTo所定义)是晚一点的日期“大于”早一点的日期。对于资历,在那里待的时间越长的人资历越高,即,您希望的开始日期越早表示资历越高

    由于Comparator的契约规定,如果compare(a,b) != 0那么compare(a,b)compare(b,a)必须具有相反的符号,那么对于如何实现ab的逆序比较,您有两种选择—返回-(a.compareTo(b))b.compareTo(a)—它们保证具有相同的符号

    它们不一定具有相同的,但对比较结果来说唯一重要的是它们是><还是==到0-尽管许多示例使用-10+1,但任何带右号的值都是正确的

  2. # 2 楼答案

    如果要更改排序顺序,请使用:

    Collections.sort(list, Collections.reverseOrder(comparator));
    

    不要玩比较仪

  3. # 3 楼答案

    比较器的compare方法期望在e1<e2e1==e2e1>e2时返回-1、0或1。因此,如果你得到的最终顺序正好是期望的倒数,那么简单地反转a和b就可以解决问题