Java优先级队列应该如何工作? [英] How is the Java priority Queue supposed to work?
问题描述
简短的故事,我正在实施一个图表,现在我正在研究Kruskal,我需要一个优先级队列。我对优先级队列的定义是具有最小密钥的元素将首先出现?这是错的吗?因为当我在队列中插入加权边(或数字)时,它们不会最终排序。
Short story, I'm implementing a graph and now I'm working on the Kruskal, I need a priority queue. My definition of a priority queue is that the element with the smallest key would come first? Is this wrong? Because when I insert the weighted edges(or numbers) in the queue they don't end up sorted.
PriorityQueue<Integer> tja = new PriorityQueue<Integer>();
tja.add(55);
tja.add(99);
tja.add(1);
tja.add(102);
tja.add(54);
tja.add(51);
System.out.println(tja);
这将打印出来; [1,54,51,102,99,55]。这不像我希望的那样排序!是的,我创建了一个进入优先级队列的comperator,该队列从edge对象中提取数字并根据该int进行比较。所以这应该有用,或者我只是完全误解了这个数据结构如何工作的整个概念?
That would print out this; [1, 54, 51, 102, 99, 55]. This is not sorted like I want them to be! And yes I made a comperator that goes into the priority queue that extracts the number from the edge object and compares based on that int. So this should work, or have I just completely misunderstood the entire concept of how this data structure works?
推荐答案
System.out.println正在调用使用迭代器的toString()方法,该方法无法保证尊重自然的顺序。来自文档:提供的迭代器方法iterator()不保证以任何特定的顺序遍历优先级队列的元素。
System.out.println is invoking the toString() method, which is using the iterator, which is not guaranteed to respect the natural ordering. From the docs: "The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order."
这篇关于Java优先级队列应该如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!