Take the 2-minute tour ×

In the below code, I want to know the significance of 10 while creating a PrioriyQueue. I know its the initial capacity but will it affect performance??

import java.util.*;

class Test {
    static class PQsort implements Comparator<Integer> { // inverse sort
        public int compare(Integer one, Integer two) {
            return two - one; // unboxing

    public static void main(String[] args) {
        int[] ia = { 1, 5, 3, 7, 6, 9, 8 }; // unordered data
        PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>(); // use
                                                                    // natural
                                                                    // order
        for (int x : ia)
        for (int x : ia)
            // review queue
            System.out.print(pq1.poll() + " ");
        PQsort pqs = new PQsort(); // get a Comparator
        PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs); // use
                                                                            // Comparator
        for (int x : ia)
            // load queue
        System.out.println("size " + pq2.size());
        System.out.println("peek " + pq2.peek());
        System.out.println("poll " + pq2.poll());
        for (int x : ia)
            // review queue
            System.out.print(pq2.poll() + " ");
share|improve this question
Did you consider reading the Javadoc before you posted? Instead of posting? –  EJP May 23 '12 at 10:18
add comment

2 Answers

up vote 1 down vote accepted

Javadoc explains:

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.

In other words, being able to specify the initial capacity is a way to optimize performance if one discovers that the queue spends too much time growing its internal array.

share|improve this answer
You may have the same question for ArrayList (and some other collections): stackoverflow.com/questions/3564837/capacity-of-arraylist –  Vakh May 23 '12 at 7:39
add comment

The API docs do explain what the capacity is. It's the size of the internal array.


Allowing you to specify an initial capacity is a small optimization. 
If you know how many entries you will need, you can save the (tiny) time 
spent growing the queue to the required size, by sizing it correctly 
from the start.
share|improve this answer
add comment

Your Answer


