# Usage of Capacity parameter in PriorityQueue

ArunaKumari Sankarram
Greenhorn
Posts: 7
Appreciate if someone explains me how the "capacity" in PriorityQueue is used?

From Java API documentation...
PriorityQueue()
Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.

I created the follwoing program and expected it to store and sort only the first 11 (default value) in the queue, however it stored and sorted all the 14 nos.

import java.util.*;
public class PQdemo {

public static void main (String[] args) {

int [] ia = {1,6,7,3,4,8,9,11,13,12,2,5,10,14};

PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>(); // use natural order

for (int x: ia) // load queue
pq1.offer(x);

for (int x:ia)
System.out.print (" " + pq1.poll());

}
}

after execution my result was : 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Ankit Garg
Sheriff
Posts: 9529
33
Hi Aruna, welcome to javaranch.

Aruna, try to use Use Code Tags when you post a source code. That way your code looks formatted. Unformatted code is hard to read. You can add code tags by wrapping your code in [code] [/code] tags. You can edit your message using button and then add code tags to it.

As far as your question goes, when the documentation says that the initial capacity is 11, it means that the priority queue will have space for 11 elements when you create the list. So the first 11 elements will be added to the queue very fast. After that if you add any elements, then the queue will be re-sized to fit any extra elements so it can be a little slower. It doesn't mean that the list is not going to be ordered after 11 elements. There is also a constructor provided to specify the initial capacity. This has advantage if you know exactly how many elements will be in the queue when you create the queue. Suppose I know that my queue will contain 25 elements. Then I can create a queue with the initial capacity of 25. By doing this, the queue will not have to be re-sized when I add elements which will speed up the task a little bit. Of course if I need to add a 26th element, I can add it but it might take more time as the queue will have to be re-sized...

ArunaKumari Sankarram
Greenhorn
Posts: 7
Ankit,
Thanks a lot for your explanation. Would you also please let me know, if there is any documentation for this or you gained the knowledge through experience?

I will post any code formatted in future and really thanks for your time and patience in explaining me that.

Ankit Garg
Sheriff
Posts: 9529
33
I don't remember exactly but I think I read this in either K&B book or Khalid Mughal book...

ArunaKumari Sankarram
Greenhorn
Posts: 7
ok, Thanks again!

Bert Bates
author
Sheriff
Posts: 8900
5
Hey guys,

You might get a priority queue question on the exam, but you won't be tested on capacities.

hth,

Bert

ArunaKumari Sankarram
Greenhorn
Posts: 7
Thanks, Bert