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

最佳答案

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

The javadoc of this method提到


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


您将不得不使用另一种方式来遍历PriorityQueue

以下应该工作:

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

10-07 19:20
查看更多