我试图建立一个优先队列,但是当我测试它时似乎有一些不一致。我覆盖了方法compareTo()
,但不知何故它返回了年龄最小的学生。这是为什么 ?不应该是22岁(最高)的学生吗?这是代码:
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());
}