【问题标题】:PriorityQueue custom sortingPriorityQueue 自定义排序
【发布时间】:2017-11-23 17:24:19
【问题描述】:

我已经为我的节点优先级队列实现了一个自定义比较器,但由于某种原因它无法正常工作。任何帮助表示赞赏。如果我的 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

【问题讨论】:

    标签: java comparator priority-queue


    【解决方案1】:

    您的 Comparator 类有一个错误。 "if" 和 "else if" 检查相同的条件。检查下面的更正版本。

    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

    【讨论】:

    • 谢谢,但现在我已经修复了它,我仍然得到相同的输出。
    • 还要注意compare 不必只返回-101,一个简单的return node1.getCost() - node2.getCost() 的行为方式应该相同。
    • @Aaron 使用减法比较整数值很容易出现溢出导致的错误。
    • @StuartMarks 谢谢,我不会想到这一点。我想在这种特定情况下,成本不可能为负数,因此不存在这种风险。
    • 或者把所有的都换成return node1.getCost().compareTo(node2.getCost());
    【解决方案2】:

    使用“foreach”浏览您的收藏会使用来自PriorityQueue.iterator()Iterator

    The javadoc of this method 提到

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

    您将不得不使用另一种方式来迭代您的 PriorityQueue

    以下应该有效:

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

    【讨论】:

      猜你喜欢
      • 2021-08-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 2014-07-18
      • 2011-12-16
      相关资源
      最近更新 更多