This question already has answers here:
The built-in iterator for java's PriorityQueue does not traverse the data structure in any particular order. Why?
                                
                                    (5个答案)
                                
                        
                4年前关闭。
            
        

我有一个Vehicles的PriorityQueue,其中有一个项目未正确订购。我认为我的compareTo中有些奇怪,但我找不到。

public class Vehicle implements Comparable<Vehicle> {

private int id;
private Calendar queueTime;
private int type;
private int size;
 }

@Override
public int compareTo(Vehicle vehicle) {
    if (this.getType() == vehicle.getType()) {
        if (this.getSize() == vehice.getSize()) {
            return (this.queueTime.compareTo(vehicle.queueTime));
        } else if (this.getSize().compareTo(vehicle.getSize()) > 0) {
            return -1;
        } else {
            return 1;
        }
    } else if (this.getType().compareTo(vehicle.getType()) > 0) {
        return -1;
    } else {
        return 1;
    }
}


我有一个主类,它创建PriorityQueue,创建一堆Vehicle对象,然后将它们添加到队列中。

Queue<Vehicle> currentQueue = new PriorityQueue<Vehicle>();
Vehicle smallPass1 = new Vehicle(1, Calendar.getInstance(), 1, 0);
Vehicle smallCargo1 = new Vehicle(2, Calendar.getInstance(), 0, 0);
Vehicle largePass1 = new Vehicle(3, Calendar.getInstance(), 1, 1);
Vehicle largeCargo1 = new Vehicle(4, Calendar.getInstance(), 0, 1);
Vehicle smallPass2 = new Vehicle(5, Calendar.getInstance(), 1, 0);
Vehicle smallCargo2 = new Vehicle(6, Calendar.getInstance(), 0, 0);
Vehicle largePass2 = new Vehicle(7, Calendar.getInstance(), 1, 1);
Vehicle largeCargo2 = new Vehicle(8, Calendar.getInstance(), 0, 1);


我期望这个输出:

Queue is: [
Vehicle [id=3, queueTime=1396824774459],
Vehicle [id=7, queueTime=1396824774459],
Vehicle [id=5, queueTime=1396824774459],
Vehicle [id=1, queueTime=1396824774458],
Vehicle [id=8, queueTime=1396824774459],
Vehicle [id=4, queueTime=1396824774459],
Vehicle [id=2, queueTime=1396824774459],
Vehicle [id=6, queueTime=1396824774459]]


但是我得到了这个:

Queue is: [
Vehicle [id=3, queueTime=1396824774459],
Vehicle [id=7, queueTime=1396824774459],
Vehicle [id=8, queueTime=1396824774459],
Vehicle [id=5, queueTime=1396824774459],
Vehicle [id=1, queueTime=1396824774458],
Vehicle [id=2, queueTime=1396824774459],
Vehicle [id=4, queueTime=1396824774459],
Vehicle [id=6, queueTime=1396824774459]]

最佳答案

您的队列和compareTo方法可能正常工作。请注意API关于它的说明:


  此类及其迭代器实现Collection和Iterator接口的所有可选方法。不保证方法iterator()中提供的Iterator以任何特定顺序遍历优先级队列的元素。如果需要有序遍历,请考虑使用Arrays.sort(pq.toArray())。


当通过操作poll,remove,peek和element从队列中检索项目时,顺序很明显。

关于java - PriorityQueue订购问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22901322/

10-10 18:22