Java: PriorityQueue initializations

杀马特。学长 韩版系。学妹 提交于 2019-12-20 01:49:30

问题


I am trying to understand the following line which initiates a Priority Queue:

PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]);

Comparing with Constructor section in the document, https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html

I couldn't figure out which Constructor it uses. Could someone please share the thought?

Also, is there a document that could better explain/define syntax (a, b) -> b[1] - a[1] ... though I could guess what it means.

Thanks a lot!


回答1:


Your construction of the PriorityQueue uses a constructor that didn't yet exist in 1.7, which is the version of the Javadocs you linked.

It uses a constructor that takes a Comparator that was added for Java 1.8, which is matched to the lambda expression you supplied.

Creates a PriorityQueue with the default initial capacity and whose elements are ordered according to the specified comparator.

Since:

1.8

Lambda expressions were introduced with Java 1.8. Here, basically you have 2 arguments and expression that are matched to a functional interface --Comparator.




回答2:


Since Java 8, there's a new constructor that has a Comparator for argument:

public PriorityQueue(Comparator<? super E> comparator)

Thus the initialization using a lambda is valid Java 8+ code.




回答3:


In Priority Queue you will essentially put user define objects, so to do it priority queue asks you how to order these objects (because priority queues are like heap data structures -- a min/max heap ) so we give it a Comparator which has a compare method ideally denoted by ((a, b) -> b[1] - a[1]) , this method give +ve, -ve or a zero result based on b > a , b < a or b = a. By this result it decides whether it should arrange the elements in ascending or descending order.

https://github.com/openjdk-mirror/jdk7u-jdk/blob/master/src/share/classes/java/util/PriorityQueue.java



来源:https://stackoverflow.com/questions/48553286/java-priorityqueue-initializations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!