gpt4 book ai didi

java - 尝试优先级队列,我的报价方法没有将项目放在最后

转载 作者:行者123 更新时间:2023-12-01 21:18:17 25 4
gpt4 key购买 nike

我的程序工作正常,直到我轮询一些项目然后添加进来,有时我的报价方法将一个项目放在队列的前面而不是后面。我添加了一些打印语句,以便人们可以看到队列中发生了什么。

import java.util.*;

public class PriorityQ {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
PriorityQueue<String> q = new PriorityQueue<String>();
String input = "";
while (!input.equals("X")) {
input = s.nextLine();
if (input.equals("O") && q.peek() == null) {
System.out.println("Buffer empty");
}
else if (!input.equals("O")) {
q.offer(input);
System.out.println(q);
}
else if (q.peek() != null && input.equals("O")) {
System.out.print("Data: ");
System.out.printf("%s ", q.peek());
q.poll();
System.out.println();
System.out.println(q);
}
}
}
}

I/O如下:

line1
[line1]
line2
[line1, line2]
line3
[line1, line2, line3]
O
Data: line1
[line2, line3]
O
Data: line2
[line3]
line1
[line1, line3]

最后一行是我的问题,它将 line1 放在 line3 的前面。感谢您的帮助:)

最佳答案

阅读PriorityQueue的javadoc :

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

println(q) 调用继承自 AbstractCollectiontoString(),后者使用 iterator(),因此打印队列将以任意顺序列出元素。

轮询已排序。迭代不是。

关于java - 尝试优先级队列,我的报价方法没有将项目放在最后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39576903/

25 4 0