我用PriorityQueue
编写了一个简单的程序,但poll()
的输出顺序与预期的顺序相反。
PriorityQueueTest.java:( junit test )
import java.util.PriorityQueue;
import junit.framework.TestCase;
import org.junit.Test;
public class PriorityQueueTest extends TestCase {
@Test
public void testPriorityQueue() {
int ids[] = { 1, 2, 3, 4, 5 };
int priorities[] = { 5, 6, 5, 4, 7 };
int outputIds[] = { 5, 2, 1, 3, 4 };
PriorityQueue<PrioTask> pq = new PriorityQueue<PrioTask>();
for (int i = 0; i < ids.length; i++) {
pq.add(new PrioTask(ids[i], priorities[i]));
}
PrioTask task;
for (int i = 0; i < ids.length; i++) {
task = pq.poll();
System.out.printf("%d, ", task.getId());
// assertEquals(task.getId(), outputIds[i]);
}
System.out.printf("\n");
}
}
class PrioTask implements Comparable<PrioTask> {
private int id;
private int priority;
public PrioTask(int id, int priority) {
this.id = id;
this.priority = priority;
}
@Override
public int compareTo(PrioTask o) {
return this.priority - o.priority;
}
public int getId() {
return id;
}
public int getPriority() {
return priority;
}
}
预期输出:5, 2, 1, 3, 4,
实际输出:4, 1, 3, 2, 5,
问题是:
compareTo()
方法错误(优先级较高的优先级属性具有较高优先级),或者我理解PriorityQueue
错误了?我刚刚添加了Integer
值的测试方法,
Integer
的测试方法:
@Test
public void testInteger() {
Integer values[] = { 5, 2, 1, 3, 4 };
Integer outputValues[] = { 5, 4, 3, 2, 1 };
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for (int i = 0; i < values.length; i++) {
pq.add(values[i]);
}
Integer value;
for (int i = 0; i < values.length; i++) {
value = pq.poll();
System.out.printf("%d, ", value);
// TODO ... why the output is in reverse order as expected ?
// assertEquals(task.getId(), outputIds[i]);
}
System.out.printf("\n");
}
输出为:1, 2, 3, 4, 5,
其他问题是:
PriorityQueue
会认为较小的值具有高优先级,是这样吗?PriorityQueue
会认为较小的值具有较高的优先级(小或大是由性质或Comparable
接口决定的。)PriorityQueue
或其他方法从poll()
检索应该会收到价值较小的项目。答案 0 :(得分:2)
你的比较器回到了前面。它应该是
@Override
public int compareTo(PrioTask o) {
return o.priority-this.priority;
}
从Javadoc回答补充问题:
此队列的 head 是与指定排序相关的至少元素。