How to create a PriorityQueue with a new comparator and NO specified initial capacity?

in Java, I don’t know how to create a new one PriorityQueuewith a new comparator, but without specifying the length of the queue? How to create it?

I know I can write:

Queue<Node> theQueue = new PriorityQueue<Node>(15,new Comparator<Node>();

But I hope that the queue can work like LinkedList, I mean, its length is not fixed, how can I declare it?

+5
source share
4 answers

There is no such constructor. According to JavaDocs , the default capacity is 11 , so you can specify this for similar behavior to the no-arg constructor PriorityQueue:

Queue<Node> theQueue = new PriorityQueue<Node>(11,new Comparator<Node>());

And yes, the line will grow if necessary.

, , , . . , . .

+7

, Comparator . , - .

+1

Java 8 , , : PriorityQueue ( )

, :

Queue<Node> theQueue = new PriorityQueue<>(new Comparator<Node>());
+1

, , Java Lambda, Java SE 8.

, :

PriorityQueue<String> pq = new PriorityQueue<>((s1, s2) -> s1.compareTo(s2));

See an example about Lambda: https://www.mkyong.com/java8/java-8-lambda-comparator-example/

0
source

All Articles