Reputation: 155
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());
}
Upvotes: 5
Views: 7409
Reputation: 44
The reason is, the queue size is recalculated for each iteration but its size is reduced within the loop.
So, instead of calculating the queue size in the for loop... calculate it outside of the for loop. This way code does not need to recalculate it for each iteration and even though the queue size is reduced within the loop, it still iterates fully to the initial size of the list.
Some thing like:
PriorityQueue<T> queue= new PriorityQueue<T> () ;
List<T> list = new ArrayList<T>();
int qSize = queue.size();
for (int i = 0 ; i< qSize; i++)
{
list.add(0, queue.poll());
}
Upvotes: 1
Reputation: 5162
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.
Upvotes: 7
Reputation: 767
ArrayList has a constructor that accepts Collection. PriorityQueue implements Collection. You don't need to iterate through queue.
PriorityQueue<T> queue= new PriorityQueue<T>();
List<T> list = new ArrayList<T>(queue);
Upvotes: 0
Reputation: 139
you are polling elements, that means you are droping them from your queue, while you wanna iterate over it.
i would recommend you to use
queue.peek()
instead.
Upvotes: -2