PriorityQueue自定义排序

时间:2017-11-23 17:24:19

标签: java comparator priority-queue

我已为节点的优先级队列实现了自定义比较器,但由于某种原因它无法正常工作。任何帮助表示赞赏。如果我的Node类实现了可比较的结果,我也会得到相同的结果。

Queue<Node> queue = new PriorityQueue<>(new Comparator<Node>()
{

        public int compare(Node node1, Node node2)
        {
            if (node1.getCost() < node2.getCost())
            {
                return -1;
            }
            else if (node1.getCost() < node2.getCost())
            {
                return 1;
            }

            return 0;
        }
});

    Node node1 = new Node(initState, null,0);
    node1.setCost(20);
    Node node2 = new Node(initState, null,0);
    node2.setCost(15);
    Node node3 = new Node(initState, null,0);
    node3.setCost(10);
    Node node4 = new Node(initState, null,0);
    node4.setCost(5);
    Node node5 = new Node(initState, null,0);
    node5.setCost(4);
    Node node6 = new Node(initState, null,0);
    node6.setCost(3);

    for (Node node : queue)
    {
        System.out.println(node.getCost());
    }

输出

  

3

     

5

     

4

     

20

     

10

     

15

2 个答案:

答案 0 :(得分:2)

您的Comparator类有错误。 &#34;如果&#34;以及&#34;否则如果&#34;检查相同的条件。请查看下面的更正版本。

new Comparator<Node>()
{

    public int compare(Node node1, Node node2)
    {
        if (node1.getCost() < node2.getCost())
        {
            return -1;
        }
        else if (node1.getCost() > node2.getCost())
        {
            return 1;
        }

        return 0;
    }
}

我认为你熟悉比较器的概念,上面是一个错字。如果不是这种情况,您可以learn more on that here

答案 1 :(得分:0)

使用“foreach”浏览您的收藏集会使用Iterator生成的PriorityQueue.iterator()

The javadoc of this method提及

  

迭代器不会以任何特定顺序返回元素。

您必须使用其他方式迭代PriorityQueue

以下内容应该有效:

while(!queue.isEmpty()) {
    Node currentNode = queue.poll();
    // ...
}