import java.util.*;
class abc {
public static void main(String args[]){
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(1);
pq.add(2);
pq.add(3);
pq.add(4);
pq.add(5);
pq.add(6);
System.out.println(pq);
pq.remove();
System.out.println(pq);
}
}
当我删除元素时,顺序会改变。 输出应根据字典排序按升序排列。但是我得到的输出是:
最佳答案
调用 System.out.println(pq);
等同于调用 System.out.println(pq.toString());
如果您查看 documentation of the the toString() method ,您会看到它指出:
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
我突出了重要的部分。所以我们需要看看 documentation of the iterator of the priority queue其中指出:
Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.
因此您的代码的输出不允许对优先级队列强加的顺序作出任何结论。
在main documentation of the PriorityQueue它说:
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()).
关于java - 无法理解 PriorityQueue 如何改变排序顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44301081/