0

I have below piece of code

        Comparator<StudentDTO> compareNames = Comparator.comparing(StudentDTO::getName);
    PriorityQueue<StudentDTO> h = new PriorityQueue<>(compareNames);

    h.offer(new StudentDTO(5, "c"));
    h.offer(new StudentDTO(2, "b"));
    h.offer(new StudentDTO(8, "z"));
    h.offer(new StudentDTO(1, "a"));

System.out.println(h);

And I am getting output as below:

[StudentDTO [rollNo=1, Name=a], StudentDTO [rollNo=2, Name=b], StudentDTO [rollNo=8, Name=z], StudentDTO [rollNo=5, Name=c]]

Not sure why Name=z is coming before Name=c. Edit: I am using java 8.

Vishnu Dahatonde
  • 179
  • 2
  • 13

1 Answers1

3

When you print PriorityQueue like this - the toString method from AbstractCollection is invoked underneath. And it uses Iterator of the extending colllection - in your case of the PriorityQueue - to travers the collection and create a String from it. And if you check the docs of PriorityQueue::iterator it returns iterator that returns elements in no particular order :

Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.

If you want to retrive elements in their priority order defined by comparator use methods like poll and remove. Considering you have overriden StudentDTO::toString method something like this will print objects from the queue also removing them from the queue :

while (!h.isEmpty()) {
    System.out.println(h.poll());
}

and the output :

StudentDTO{rollNo=1, name='a'}
StudentDTO{rollNo=2, name='b'}
StudentDTO{rollNo=5, name='c'}
StudentDTO{rollNo=8, name='z'}
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63