对象无法正确添加

时间:2013-03-01 01:01:35

标签: java priority-queue

我正在尝试创建一个优先级队列并使用比较器,但是当我添加对象时,会添加最后一个对象,而早期的对象不会出现在队列中。

以下是代码:

public class CustomerCompare implements Comparator<Customer>{
    @Override
    public int compare(Customer c1, Customer c2) {
        if(c1.priority>c2.priority)
            return 1;
        if(c1.priority>c2.priority)
            return -1;
        return 0;

    }
}      

public class PQueue {
    public static void main(String[] args) {
        Comparator<Customer> comparator = new CustomerCompare();
        PriorityQueue<Customer> queue = new PriorityQueue<Customer>(5, comparator);
        queue.add(new Customer("c1", 1));
        System.out.println("Queue is now :" + queue);
        queue.add(new Customer("c2", 7));
        System.out.println("Queue is now :" + queue);
        queue.add(new Customer("c3", 3));
        System.out.println("Queue is now :" + queue);
        queue.add(new Customer("c4", 6));
        System.out.println("Queue is now :" + queue);
        queue.add(new Customer("c5", 5));

        System.out.println("Elements in queue");
        while (true) {
            Customer currentCust = queue.poll();
            if (currentCust == null) {
                break;
            }
            System.out.print(currentCust.getCustomerNum() + " <-- ");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您的>似乎使用了<代替compare,将其更改为:

if (c1.priority > c2.priority)
    return 1;
if (c1.priority < c2.priority)
    return -1;
return 0;

编辑:或者更简单:

return Integer.valueOf(c1.priority).compareTo(c2.priority);

编辑2:或使用Java 7:

return Integer.compare(c1.priority, c2.priority);