PriorityQueue订购问题

时间:2014-04-06 23:31:33

标签: java

我有一个PriorityQueue of Vehicles,其中有一个项目没有正确订购。我认为我的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]]

1 个答案:

答案 0 :(得分:7)

您的队列和compareTo方法可能正常运行。请注意API所说的内容:

  

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

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