PriorityQueue
class does not guarantee the order if iterator()
method is used.
Javadoc explicitly defines it here as:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
You just need to modify the main
as below.
import java.util.Arrays;
import java.util.PriorityQueue;
public class BookQueue {
public static void main(String[] args) throws BookException {
PriorityQueue<Book> pq = new PriorityQueue<Book>();
pq.offer(new Book(32, true, "Green eggs and ham", 12));
pq.offer(new Book(42, true, "Hop on Pop", 11));
pq.offer(new Book(20, true, "Lorax", 19));
pq.offer(new Book(20, false, "Lorax", 19));
pq.offer(new Book(22, true, "Cat in the hat", 10));
// Iterator itr = pq.iterator();
// System.out.println("\n");
// while(itr.hasNext()){
// System.out.println(itr.next());
//}
Book[] books = new Book[pq.size()];
Arrays.sort(pq.toArray(books));
System.out.println("\n");
for (int i = 0; i < books.length; i++) {
System.out.println(books[i]);
}
}
}
Hope this helps. Also you can try to implement the Comparator
and pass into the Arrays.sort(T[], Comparator)
if you need different sorting approaches as detailed in Comparator vs Comparable.