user2326847
user2326847

Reputation: 145

Priority queue implementation

I was trying to build a priority queue but there seems to be some inconsistency when I tested it. I overrode method compareTo() but somehow it return student with the youngest age. Why is that ? Shouldn't it be the student with age 22 (highest) ? Here is the code:

public class Student implements Comparable<Student> {

   private String name;
   private int age;

   public Student(int i) {
      age = i;
   }
   public int getAge(){
    return this.age;
   }

   public int print(){
    return age; 
   }
   @Override
   public int compareTo(Student s) {
    if(this.age < s.getAge()){return -1;}
    else if(this.age > s.getAge()){return 1;}
    else{return 0;}
   }
    public static void main(String[] args) {
        Queue<Student> q = new PriorityQueue<Student>();
        q.offer(new Student(21));
        q.offer(new Student(18));
        q.offer(new Student(22));

        Student s = q.poll();
        System.out.println(s.print());
} 

Upvotes: 0

Views: 539

Answers (1)

Antimony
Antimony

Reputation: 39451

Java's java.util.PriorityQueue is defined as returning the least element, not the largest element, as you can find by checking the docs.

The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.

Whether a priority queue is based on a minimum or maximum depends on the language and library, but minimum queues are by fat the most common from what I've seen.

Upvotes: 2

Related Questions