簡體   English   中英

Java 中的比較器和 PriorityQueue 是如何工作的?

[英]How comparator and PriorityQueue in Java works?

這是我用來扭轉Java中priorityQueue正常工作的代碼。 但我不明白我放在括號內的 lambda function 做了什么。 有人可以解釋一下。

PriorityQueue pq = new PriorityQueue<>( (a,b) -> b - a );

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b - a);
        
        pq.add(2);
        pq.add(4);
        pq.add(1);
        pq.add(100);
        
        System.out.println(pq);
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        System.out.println(pq.remove());
        
    }
} 

比較 function 是一個 function ,當第一個參數應該在第二個之前排序時,必須返回任何小於0的值,當第二個參數應該在第一個之前排序時,任何大於0的值都必須返回,如果兩者對於排序等價,則返回0

它在內部的PriorityQueue中使用,通過將其結果與 0 進行比較來確定元素的相對順序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM