简体   繁体   English

自定义比较器-Java

[英]Custom Comparator - Java

I am having trouble understanding the Sorting using a Custom Comparator in Java. 我在使用Java中的“使用自定义比较器”时无法理解排序。

Queue<Integer> q = new PriorityQueue<>(arr.length, (a,b) -> ab);

gives me ascending order sort, while 给我升序排序,而

Queue<Integer> q = new PriorityQueue<>(arr.length, (a,b) -> ba);

gives me a descending order sort. 给我降序排列。

What I can not understand is how is this working? 我不明白这是怎么工作的? Is b the incoming element and a already in the array or vice versa? b是传入元素,而a已经在数组中,反之亦然吗? Also, how is the ascending or descending order obtained? 另外,如何获得升序或降序?

If ab > 0 , this means that a>b , so shouldn't b be infront of a in ascending order? 如果ab > 0 ,这意味着a>b ,那么b不应该以a的升序ab前面吗?

Comparison-based sorts distinguish values by determining whether or not they are < , = , or > . 基于比较的排序通过确定值是<=还是>来区分值。

For example, 3 < 4 , 4 = 4 , 4 > 3 . 例如3 < 4 4 = 4 4 > 3

Java Comparators use the convention that Java比较器使用以下约定

  • cmp(a, b) < 0 means a < b cmp(a, b) < 0表示a < b
  • cmp(a, b) = 0 means a = b cmp(a, b) = 0意味着a = b
  • cmp(a, b) > 0 means a > b cmp(a, b) > 0表示a > b

Note that this means if cmp(x, y) = x - y , then you get the normal ordering for the integers. 请注意,这意味着如果cmp(x, y) = x - y ,那么您将获得整数的常规排序。 You can check yourself that cmp(x, y) = -(x- y) = y - x gives you the reverse ordering. 您可以检查一下自己, cmp(x, y) = -(x- y) = y - x给您相反的顺序。

When sorting (or doing something else that moves generic elements around by their order, like a PriorityQueue), the algorithm will (repeatedly) consult the comparator to determine whether or not values it has been given are < , = , or > . 排序时(或执行其他操作以按其顺序移动通用元素时,例如PriorityQueue),该算法将(反复)咨询比较器以确定是否已赋予它的值是<=>

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

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