可能的重复:
为什么java中的PriorityQueue会出现这种奇怪的顺序?
请参阅下面的代码:
public static void main(String[] args) {
Queue<String> q = new PriorityQueue<String>();
q.offer("car");
q.offer("airplane");
q.offer("bicycle");
Iterator<String> i = q.iterator();
while(i.hasNext())
System.out.print(i.next() + " ");
}
有人可以解释一下为什么输出是
airplane car bicycle
代替
airplane bicycle car
?
Since 在 API 中它表示优先级队列的元素按照其自然顺序排序。
根据迭代器的 javadoc:
迭代器不以任何特定顺序返回元素。
但是,第一项(头)保证是最小的。所以这应该打印出你期望的内容:
public static void main(String[] args) throws Exception {
Queue<String> q = new PriorityQueue<String>();
q.offer("car");
q.offer("airplane");
q.offer("bicycle");
String e = null;
while ((e = q.poll()) != null) {
System.out.println(e);
}
}
如果你想对迭代进行排序,你需要使用不同的结构,例如TreeSet
如果你没有重复的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)