JAVA中具有迭代器的PriorityQueue

时间:2018-11-28 19:00:47

标签: java

我期望这样的结果。 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());
        }
    }
}

0 个答案:

没有答案