Search code examples
javalistpriority-queue

Priority Queue to List. not adding properly


I am trying to copy items out of a priority queue and into an ArrayList. for some reason, when there are three or four items, it stops after adding two items to the list. If there are 5 items, it stops after copying 3 items to the list. What am I doing wrong?

PriorityQueue<T> queue= new PriorityQueue<T> () ; 
List<T> list = new ArrayList<T>();

 for (int i = 0 ; i< queue.size(); i++)
        {
           list.add(0, queue.poll());
        }

Solution

  • Try the following code:

    PriorityQueue<T> queue= new PriorityQueue<T> () ; 
    List<T> list = new ArrayList<T>();
    
    while(!queue.isEmpty()){
           list.add(0, queue.poll());
        }
    

    An example:

    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    class Main{
        public static void main (String[] args) {
            PriorityQueue<Integer> queue = new PriorityQueue<>();
            queue.add(5);
            queue.add(4);
            queue.add(3);
            queue.add(2);
            queue.add(1);
            List<Integer> list = new ArrayList<>();
            while(!queue.isEmpty()) {
                list.add(0,queue.poll());
            }
            System.out.println(list);  // Prints [5, 4, 3, 2, 1]
    
        }
    }
    

    Why your for loop is not working:

    Consider iteration 1: i = 0 and i <

    queue.size() = 5 queue = {5,4,3,2,1} list = {}

    After iteration 1:

    queue = {5,4,3,2} list = {1} i = 1

    At iteration 2: i = 1 i < queue.size() = 4 queue = {5,4,3,2} list = {1}

    After iteration 2: queue = {5,4,3} list = {1,2} i = 2

    At iteration 3: i = 2 i < queue.size() = 3 queue = {5,4,3,2} list = {1}

    After iteration 3: queue = {5,4} list = {1,2,3} i = 3

    At iteration 4: i = 3 i < queue.size() = 3? = > False

    Quit the loop!

    So you are quitting the for loop when still queue = {5,4} and all the elements are not added to list.