我期望这样的结果。 JAVA-> 1,Python-> 2,C ++-> 3 但是结果是 JAVA-> 1,C ++-> 3,Python-> 2
有什么问题?下面是我的代码。
package priorityqueue;
import java.util.Iterator;
import java.util.PriorityQueue;
class Grade implements Comparable<Grade> {
private String subject;
private int grade;
public Grade(String subject, int grade) {
this.subject = subject;
this.grade = grade;
}
public int compareTo(Grade g) {
return this.grade - g.grade;
}
public String toString() {
return "sub : " + subject + " -> " + "grade : " + grade;
}
}
public class PriorityQueueCompare {
public static void main(String[] args) {
PriorityQueue<Grade> pq = new PriorityQueue<>();
pq.add(new Grade("Python", 2));
pq.add(new Grade("C++", 3));
pq.add(new Grade("JAVA", 1));
for(Iterator<Grade> itr = pq.iterator(); itr.hasNext();) {
System.out.println(itr.next());
}
}
}