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());
}