我已經創建了一個優先級隊列,它插入對象並將它們與成本參數進行比較,當兩個成本相等時它應該保持排隊順序,但是我在調試一次後發現它已排入隊列中,時間不是這樣的順序,但我沒有得到我的代碼有什麼問題我找不到任何其他職位幫助。PriorityQueue無法正常工作
import java.util.*;
import java.lang.*;
import java.io.*;
class Node implements Comparable<Node>
{
int x, y, dir;
Node(int x, int y, int dir)
{
this.x = x;
this.y = y;
this.dir = dir;
}
public int compareTo(Node o)
{
if (Ideone.cost[o.x][o.y] == Ideone.cost[x][y]) {
return 1;
} else {
int d = Ideone.cost[x][y] - Ideone.cost[o.x][o.y];
if (d > 0) {
return 1;
} else {
return -1;
}
}
}
}
class Ideone
{
public static int[][] cost;
static PriorityQueue<Node> p;
public static void main(String[] args)
throws Exception
{
p = new PriorityQueue<Node>();
cost = new int[13][11];
for (int[] row : cost)
Arrays.fill(row, -1);
cost[0][8] = 366564;
cost[2][9] = 368282;
cost[1][3] = 368282;
cost[4][9] = 368282;
cost[0][9] = 376564;
cost[1][9] = 372423;
cost[5][9] = 372423;
cost[0][3] = 436564;
cost[7][0] = 378282;
cost[2][10] = 378282;
cost[4][10] = 378282;
cost[0][4] = 382423;
p.add(new Node(0, 8, 8));
p.add(new Node(2, 9, 8));
p.add(new Node(1, 3, 7));
p.add(new Node(4, 9, 2));
p.add(new Node(0, 9, 8));
p.add(new Node(1, 9, 8));
p.add(new Node(5, 9, 2));
p.add(new Node(0, 3, 6));
p.add(new Node(7, 0, 3));
p.add(new Node(2, 10, 8));
p.add(new Node(4, 10, 2));
p.add(new Node(0, 4, 7));
while (p.size() != 0) {
Node n1 = p.poll();
System.out.println(n1.x + " " + n1.y + " " + cost[n1.x][n1.y]);
}
}
}
輸出是
0 8 366564
1 3 368282
2 9 368282
4 9 368282
5 9 372423
1 9 372423
0 9 376564
4 10 378282
2 10 378282
7 0 378282
0 4 382423
0 3 436564
,但我期待:
0 8 366564
2 9 368282
1 3 368282
4 9 368282
1 9 372423
5 9 372423
0 9 376564
7 0 378282
2 10 378282
4 10 378282
0 4 382423
0 3 436564
請參閱API [PriorityQueue](https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html) - 引用:'關係被任意破壞。「 – copeg
但我返回1來指定新插入的值大於以前的值並將其放在末尾 –
@JeevansaiJinne您可以將插入順序作爲附加字段添加,以避免丟失該信息。 –