带有比较器实现的Java PriorityQueue未返回字符串的相反顺序 PriorityQueue q2=新的PriorityQueue(15,新的比较器(){ @凌驾 公共整数比较(字符串o1、字符串o2){ //系统输出打印Ln(o1+“--”+o2); 返回o2.compareTo(o1); } }); //System.out.println(q2.peek()); //q2.要约; q2.要约(“A”); q2.要约(“L”); q2.要约(“Z”); q2.要约(“J”); q2.要约(“X”); 系统输出打印项次(q2);
上述代码的输出为[Z,X,L,A,J] 而不是[Z,X,L,J,A] 我无法找出我的代码有什么问题根据,优先级队列是: 基于优先级堆的无限优先级队列 通过查看源代码,我们可以在上面看到支持对象[]的声明:带有比较器实现的Java PriorityQueue未返回字符串的相反顺序 PriorityQueue q2=新的PriorityQueue(15,新的比较器(){ @凌驾 公共整数比较(字符串o1、字符串o2){ //系统输出打印Ln(o1+“--”+o2); 返回o2.compareTo(o1); } }); //System.out.println(q2.peek()); //q2.要约; q2.要约(“A”); q2.要约(“L”); q2.要约(“Z”); q2.要约(“J”); q2.要约(“X”); 系统输出打印项次(q2);,java,collections,priority-queue,Java,Collections,Priority Queue,上述代码的输出为[Z,X,L,A,J] 而不是[Z,X,L,J,A] 我无法找出我的代码有什么问题根据,优先级队列是: 基于优先级堆的无限优先级队列 通过查看源代码,我们可以在上面看到支持对象[]的声明: PriorityQueue<String> q2=new PriorityQueue<String> (15, new Comparator<String>() { @Override public int compare(
PriorityQueue<String> q2=new PriorityQueue<String> (15, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
//System.out.println(o1+" -- "+o2);
return o2.compareTo(o1);
}
});
//System.out.println(q2.peek());
//q2.offer("s");
q2.offer("A");
q2.offer("L");
q2.offer("Z");
q2.offer("J");
q2.offer("X");
System.out.println(q2);
/**
*表示为平衡二进制堆的优先级队列:两个
*队列[n]的子级是队列[2*n+1]和队列[2*(n+1)]。这个
*优先级队列由比较器或元素的优先级排序
*自然排序,如果比较器为空:对于
*heap和n的每个子代d,n还想添加这样一个信息:如果您希望队列结果按顺序排列,那么您可以轮询整个队列并清空它
/**
* Priority queue represented as a balanced binary heap: the two
* children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The
* priority queue is ordered by comparator, or by the elements'
* natural ordering, if comparator is null: For each node n in the
* heap and each descendant d of n, n <= d. The element with the
* lowest value is in queue[0], assuming the queue is nonempty.
*/
将打印出您期望的内容。我将q2对象传递给System.out.println(),因此调用tostring()方法,因此无法保证检索对象的顺序。就像您提到的q2一样,应该调用poll()来获取队列的预期行为。
while (q2.size() > 0) {
System.out.println(q2.poll());
}