java 如何使用新的比较器创建一个 PriorityQueue 并且没有指定的初始容量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15098731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a PriorityQueue with new comparator and NO specified initial capacity?
提问by lkkeepmoving
in Java, I don't know how to create a new PriorityQueue
with new comparator but without given the queue length? How can I create it?
在 Java 中,我不知道如何PriorityQueue
用新的比较器创建一个新的,但没有给出队列长度?我该如何创建它?
I know I can write:
我知道我可以写:
Queue<Node> theQueue = new PriorityQueue<Node>(15,new Comparator<Node>();
But I hope the queue can works like LinkedList
, I mean its length is not fixed, how can I declare it?
但我希望队列可以像 一样工作LinkedList
,我的意思是它的长度不固定,我该如何声明?
采纳答案by Matt Ball
There is no such constructor. As per the JavaDocs, the default capacity is 11, so you could specify that for analogous behavior to the no-arg PriorityQueue
constructor:
没有这样的构造函数。根据 JavaDocs,默认容量为 11,因此您可以将其指定为与无参数PriorityQueue
构造函数类似的行为:
Queue<Node> theQueue = new PriorityQueue<Node>(11,new Comparator<Node>());
And yes, the queue will grow if it needs to.
A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically. The details of the growth policy are not specified.
优先级队列是无界的,但具有控制用于存储队列中元素的数组大小的内部容量。它始终至少与队列大小一样大。当元素被添加到优先级队列时,它的容量会自动增加。增长政策的细节没有具体说明。
回答by Sean Landsman
I'm afraid theres no way to specify only a Comparator
without specifying an initial capacity. Note that this is only the initial capacity - the queue can grow from this initial value.
恐怕没有办法只指定一个Comparator
而不指定初始容量。请注意,这只是初始容量 - 队列可以从这个初始值增长。
回答by Joris Kinable
Starting from Java version 8 there's a new constructor which can do what you ask for: PriorityQueue(Comparator comparator)
从 Java 版本 8 开始,有一个新的构造函数可以满足您的要求:PriorityQueue(Comparator Comparator)
So you would get:
所以你会得到:
Queue<Node> theQueue = new PriorityQueue<>(new Comparator<Node>());
回答by Summer Jinyu Xia
You can create a priority queue with self-defined comparator without fixing the size by using Java Lambda, a feature in Java SE 8.
您可以使用 Java SE 8 中的一项功能 Java Lambda 创建具有自定义比较器的优先级队列,而无需固定大小。
For example, you can do:
例如,您可以执行以下操作:
PriorityQueue<String> pq = new PriorityQueue<>((s1, s2) -> s1.compareTo(s2));
PriorityQueue<String> pq = new PriorityQueue<>((s1, s2) -> s1.compareTo(s2));
See example about Lambda: https://www.mkyong.com/java8/java-8-lambda-comparator-example/
请参阅有关 Lambda 的示例:https: //www.mkyong.com/java8/java-8-lambda-comparator-example/