【问题标题】:How does Collection.sort(List<T>,Comparator<T>) work with the order of input? [closed]Collection.sort(List<T>,Comparator<T>) 如何处理输入顺序? [关闭]
【发布时间】:2015-06-05 20:36:14
【问题描述】:

例如,如果我想用 ID 对人进行排序,并且我编写了一个内部类来实现比较器,例如

public class IDCompare implements Comparator<People>{

    // this order of compare will sort in ascending order
    @Override
    public int compare(People o1, People o2) {
        return o1.getID() - o2.getID();
    }
    // this order of compare will sort in descending order
    @Override
    public int compare(People o1, People o2) {
        return o2.getID() - o1.getID();
    }
}

Collection.sort()方法是如何知道排序的顺序并根据输入的顺序实现my的?

【问题讨论】:

  • 你试过编译那个代码吗?
  • 如你所说,顺序由比较函数决定
  • (另外,你真的不应该使用这种方法来实现比较。它会导致极端值的问题。)
  • 另外,当不提供比较器时,您只能对可比较对象进行排序,它们自己定义它们的顺序

标签: java sorting collections


【解决方案1】:

如 Comparator 接口文档中所述,compare(T o1, To2) 方法必须返回:

作为第一个参数的负整数、零或正整数小于、等于或大于第二个参数。

这正是您的代码正在做的事情:

  • 当o1.getID()小于o2.getID()时,减法返回负数。
  • 当o1.getID() 等于o2.getID() 时,减法返回零。
  • 当o1.getID() 大于o2.getID() 时,减法返回一个正数。

生成的“符号”作为回报用于对集合进行排序。

请注意,正如 Jon Skeet 在 cmets 中所说的那样,极端值可能会由于溢出而导致问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    相关资源
    最近更新 更多