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?