【发布时间】:2012-09-04 08:29:08
【问题描述】:
我阅读了有关 PriorityQueue 的文档和我能找到的所有内容,但仍然不明白为什么输出如此奇怪我的意思是我无法理解添加顺序,谁能解释一下?
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.offer("2");
System.out.println("add 2 : " + pq);
pq.offer("4");
System.out.println("add 4 : " + pq);
System.out.println(pq.peek() + " ");
pq.offer("1");
System.out.println("offer 1 : " + pq);
pq.offer("3");
System.out.println("add 3 : " + pq);
pq.remove("1");
System.out.println("remove 1 : " + pq);
输出:
add 2 : [2]
add 4 : [2, 4] <- why 4 goes there
offer 1 : [1, 4, 2] <- why 1 goes first
add 3 : [1, 3, 2, 4] <- why reorder
remove 1 : [2, 3, 4] <- again
【问题讨论】:
-
元素在heap order.
-
需要考虑的是
PriorityQueue是否实现toString,它对String中的值进行排序。由于toString似乎在AbstractCollection中实现,我建议它可能不会。尝试使用poll以正确的顺序取出元素。 -
@JohnB 来自 AbstractCollection:“字符串表示由集合元素的列表组成,按其迭代器返回的顺序排列,括在方括号 ("[]") 中。”如果 PriorityQueue 本身没有覆盖该方法,那么应该保证它是有序的(尽管不一定是您所期望的)。
-
@AnthonyGrist:“迭代器不会以任何特定顺序返回元素。” docs.oracle.com/javase/6/docs/api/java/util/…
标签: java algorithm data-structures collections