In the below code, I want to know the significance of 10 while creating a PrioriyQueue. I know its the initial capacity but what does it mean?? I replace 10 with any positive number and the output remains same.

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)
            pq1.offer(x);
        for (int x : ia)
            // review queue
            System.out.print(pq1.poll() + " ");
        System.out.println("");
        PQsort pqs = new PQsort(); // get a Comparator
        PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs); // use
                                                                            // Comparator
        for (int x : ia)
            // load queue
            pq2.offer(x);
        System.out.println("size " + pq2.size());
        System.out.println("peek " + pq2.peek());
        System.out.println("size " + pq2.size());
        System.out.println("poll " + pq2.poll());
        System.out.println("size " + pq2.size());
        for (int x : ia)
            // review queue
            System.out.print(pq2.poll() + " ");
    }
}

PriorityQueue uses a private array to hold the queue. It automatically re-sizes the array when needed. By specifying an initial capacity you set the initial size of that array. Its just an optimisation thing - if you know how big your queue will be then the array can be made just big enough without needing to be re-sized. But it is just optimisation - the result of ruunning the program will be the same regardless. It may just use a little less memory, or run a little bit faster. Igniore it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.