我有一个类Student,它实现了Comparable,如下所示,因为我想将Student的对象放在优先级队列中,并让拥有较早注册日期的学生具有更高的优先级。
public class Student implements Comparable{
private String fullName;
private Date registrationDate;
public Student(String fullname){
this.fullName = fullName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
@Override
public int compareTo(Object obj) {
Student student = (Student) obj;
if(getRegistrationDate().before(student.getRegistrationDate())){
return 1;
}else if(getRegistrationDate().after(student.getRegistrationDate())){
return -1;
}
return 0;
}
}
在main方法中,我正在创建学生对象,设置注册日期并将它们放入优先级队列
public class School {
public static void main(String args[]) {
//list of students
Student student1 = new Student("John Doe");
Date dateStudent1Joined = new GregorianCalendar(2014, Calendar.JULY, 1).getTime();
student1.setRegistrationDate(dateStudent1Joined);
Student student2 = new Student("Mary Penn");
Date dateStudent2Joined = new GregorianCalendar(2014, Calendar.JULY, 2).getTime();
student2.setRegistrationDate(dateStudent2Joined);
Student student3 = new Student("George Coats");
Date dateStudent3Joined = new GregorianCalendar(2014, Calendar.JULY, 3).getTime();
student3.setRegistrationDate(dateStudent3Joined);
Student student4 = new Student("Tony Case");
Date dateStudent4Joined = new GregorianCalendar(2014, Calendar.JULY, 4).getTime();
student4.setRegistrationDate(dateStudent4Joined);
Student student5 = new Student("Ben Thomas");
Date dateStudent5Joined = new GregorianCalendar(2014, Calendar.JULY, 5).getTime();
student5.setRegistrationDate(dateStudent5Joined);
//create a queue data structure to hold students
PriorityQueue<Student> studentQueue = new PriorityQueue<Student>();
//add students to queue
studentQueue.offer(student1);
studentQueue.offer(student2);
studentQueue.offer(student3);
studentQueue.offer(student4);
studentQueue.offer(student5);
//print names of people in queue
for(Student student : studentQueue){
String studentName = student.getFullName();
System.out.println(studentName);
System.out.println("");
}
studentQueue.poll();
for(Student student : studentQueue){
String studentName = student.getFullName();
System.out.println(studentName);
}
}
}
在School.java中的第一个for循环中,我打印出队列中所有学生的名字,以确保它们具有正确的优先级,即具有较早注册日期的学生位于队列前面。这里的结果就是我所期待的,因为John Doe加入了第一,Ben Thomas加入了最后。
John Doe
Mary Penn
George Coats
Tony Case
Ben Thomas
但是,当我在优先级队列上调用poll()方法时,John Doe被删除但是优先级队列的顺序不再有意义,第二个for循环的输出是
Mary Penn
Tony Case
George Coats
Ben Thomas
Mary Penn处于正确的位置,但如果前一个优先级队列中的顺序仍然存在,那么George Coats应该来到Tony Case之前,我在这里做错了什么?