1

The compareTo function that I am using in my class

public int compareTo(Book b) {  
    if(id>b.id){  
        return 1;  
    }else if(id<b.id){  
        return -1;  
    }else{  
    return 0;  
    }

}

When I add a priorityQueue, with ids in the order 12 99 89 55 40 4, the output I get is:

4
40
12
99
55
89

The code which I use to iterate the PriorityQueue is:

Iterator it = queue.iterator();
while(it.hasNext()){
  Book b = (Book)it.next();
  System.out.println(b.id);
}

What could be the problem for such output? Once I invoke queue.remove() and then iterate, the order seems correct.

daredevil11
  • 107
  • 14

1 Answers1

2

The iterator of a PriorityQueue is not guaranteed to return the elements in the order defined by the Comparable implementation of your element class (Book).

From the Javadoc of PriorityQueue:

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. 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()).

Eran
  • 387,369
  • 54
  • 702
  • 768