gpt4 book ai didi

java - 为什么我的队列对输入字符串的排序与先进先出的基础不同?

转载 作者:行者123 更新时间:2023-12-01 07:17:33 24 4
gpt4 key购买 nike

我正在尝试使用队列,但队列正在自行重组,我不知道为什么

其他使用队列的人似乎都工作正常,并且似乎没有人遇到这个问题

public static void main(String[] args){
PriorityQueue<String> cue = new PriorityQueue<String>();
cue.offer("this");
cue.offer("that");
cue.offer("then");
System.out.printf("%s \n", cue);
System.out.printf("%s \n", cue.peek());
cue.poll();
System.out.printf("%s \n", cue);
}

我希望它打印:

[this, that, then]
this
[that, then]

但是它打印:

[that, this, then]
that
[then, this]

我就是不知道为什么

最佳答案

来自PriorityQueue的java文档:

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering

所以这是设计使然

您可以使用java.util.LinkedList(它实现了Queue接口(interface)并且将像先进先出队列一样工作),并且会给您预期的结果订购

关于java - 为什么我的队列对输入字符串的排序与先进先出的基础不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54631653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com