0

I have an object called Person with an attribute name, and a priority queue of Persons called pq. I have overridden the compareTo function of the Person class to sort them in reverse alphabetical order:

    @Override
    public int compareTo(Person p)
        return p.getName().compareTo(this.name);

I then added the following names:

    PriorityQueue<Person> pq = new PriorityQueue<>();
    pq.add(new Person("Ben"));
    pq.add(new Person("Ben"));
    pq.add(new Person("Adam"));
    pq.add(new Person("Zedd"));
    System.out.println(pq);

But from the output you can see the sort doesnt work properly:

[Name: Zedd, Name: Ben, Name: Adam, Name: Ben]

If however, I swap the order of the comparators in the compareTo function so it looks like this:

return this.name.compareTo(p.getName());

Then the output works fine for regular alphabetical order:

[Name: Adam, Name: Ben, Name: Ben, Name: Zedd]

Why is this happening?

rohaldb
  • 589
  • 7
  • 24
  • 1
    Priority queue sorting is shown when you remove items from the queue, not for when you print them out. – Hovercraft Full Of Eels Aug 06 '18 at 01:55
  • 1
    The priority queue's `toString()` method uses the queue's iterator to form the output string. From the [docs for `PriorityQueue`](https://docs.oracle.com/javase/9/docs/api/java/util/PriorityQueue.html): "The Iterator ... [is] not guaranteed to traverse the elements of the priority queue in any particular order." The only guarantee is that the head (the element returned by `peek()` or `poll()`) is the least element (or one of them, if there are ties). – Ted Hopp Aug 06 '18 at 01:57
  • 1
    https://docs.oracle.com/javase/9/docs/api/java/util/PriorityQueue.html mentioned that `This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() and the Spliterator provided in method spliterator() are 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()). ` – caot Aug 06 '18 at 02:05

0 Answers0