I am using a priorityQueue to implement BFS. I want to maintain the insertion order in the case of equal priority while inserting and also after poping.
I overrode the equals method as shown below and the insertion order is maintained as expected while inserting.
But, once I do a remove or poll, the order of the elements changes.
How can I maintain the insertion order even on poll?
class Cell implements Comparable<Cell>{
int v;
int dis;
public Cell(int v, int dis) {
this.v = v;
this.dis = dis;
}
public int compareTo(Cell c2) {
if((this.dis > c2.dis)) {
return 1;
} else if(this.dis < c2.dis) {
return -1;
}
return 0;
}
public boolean equals(Object o) {
if(!(o instanceof Cell)) {
return false;
}
Cell c = (Cell) o;
if(this.dis == c.dis) {
return true;
}
return false;
}
public String toString() {
return v+" ";
}
}
PriorityQueue<Cell> pq = new PriorityQueue<Cell>();
pq.offer(new Cell(0,0));
vis[0] = true;
while(!pq.isEmpty()) {
Cell c = pq.peek();
int adj;
//let's suppose getAdjVertex method will return 1,2,3
while((adj = getAdjVertex(c.v,list.get(c.v),vis)) != -1) {
vis[adj] = true;
pq.offer(new Cell(adj, c.dis+1));
}
System.out.println("pq1 = " + pq); //Here the order is correct
//pq1 = [0 , 1 , 2 , 3 ]
pq.remove(c);
System.out.println("pq = " + pq); // Here the order is changed
//pq = [3 , 1 , 2 ]
}
In the code snippet above,
I expect pq
to be [1 , 2 , 3].