简体   繁体   English

java 比较器在内部如何工作?

[英]How does java comparator work internally?

class Checker implements Comparator<Player> {
    @Override
    public int compare(Player p1, Player p2) {
        if (p1.score == p2.score) {
            return p1.name.compareTo(p2.name);
        } else {
            return p2.score - p1.score;
        }
    }
}

how does p2.score - p1.score make it descend while p1.score - p2.score makes is ascend p2.score - p1.score 如何使其下降而 p1.score - p2.score 使其上升

how does a positive or negative integer or zero return sort the objects?正整数或负整数或零返回如何对对象进行排序? whats going on internally内部发生了什么

please help thanks请帮忙谢谢

From the Comparator 's documentation :来自Comparator的文档

A comparison function, which imposes a total ordering on some collection of objects.一个比较函数,它对某些对象集合进行总排序。 ... ...

And from Comparator:compare 's documentation :来自Comparator:compare的文档

... ...

Returns:返回:

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.负整数、零或正整数作为第一个参数小于、等于或大于第二个参数。

Thus, the Comparator only defines the order.因此, Comparator只定义顺序。 It is up to the sorting algorithm to use this information and actually sort the data structure.使用此信息并实际对数据结构进行排序取决于排序算法。 If we take a look how, eg, Quicksort and Merge Sort work, we see that these algorithms only need to know whether some element a is smaller, equal or larger than b , which is the information that a Comparator provides (by returning a value < 0 , = 0 or > 0 ).如果我们看看QuicksortMerge Sort是如何工作的,我们就会发现这些算法只需要知道某个元素a是否小于、等于或大于b ,这是Comparator提供的信息(通过返回一个值< 0 , = 0> 0 )。

Now let us explain how a - b makes it sort in ascending order (lets give this Comparator the name asc ), while b - a makes it sort in decreasing order ((lets give this Comparator the name desc ): We have to look at three different cases for the two Comparator s.现在让我们解释一下a - b如何让它按升序排序(让这个Comparator命名为asc ),而b - a让它按降序排序((让这个Comparator命名为desc ):我们必须看看两个Comparator的三种不同情况。

First, suppose that a > b .首先,假设a > b Then然后

  • a - b > 0 , thus a is "larger" than b according to asc a - b > 0 ,因此a大于“” b根据asc
  • b - a < 0 , thus a is "smaller" than b according to desc b - a < 0从而a小于“” b根据desc

Next, suppose that a < b .接下来,假设a < b Then然后

  • a - b < 0 thus a is "smaller" than b according to asc a - b < 0从而a小于“” b根据asc
  • b - a > 0 , thus a is "larger" than b according to desc b - a > 0 ,从而a大于“” b根据desc

Finally, suppose that a == b .最后,假设a == b Then a - b == b - a == 0 and the elements are "equal" according to both Comparator s.然后a - b == b - a == 0并且元素根据两个Comparator都是“相等的”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM