Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

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?

like image 451
lkkeepmoving Avatar asked Feb 26 '13 20:02

lkkeepmoving


1 Answers

Modern answer, as of 2021: https://stackoverflow.com/a/30015986/139010


Pre-Java-8 answer, for posterity:

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:

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.x

like image 192
Matt Ball Avatar answered Sep 23 '22 07:09

Matt Ball