VedhaR VedhaR - 15 days ago 5x
Java Question

PriorityQueue is removing last element added (acting like a lifo)

I need another pair of eyes to look at this problem. I have implemented both a Depth first Search and Breadth First Search for a problem I am trying to solve. The Queue/stack used based on the search uses Node objects.

The problem is, both search algorithms are returning the same sequence. After looking into it more, it seems that the Priority Queue in the BFS algorithm is making the newest element that is added the HEAD of the queue.

I have also tried changing the datastructure as follow as it still gives the same result.

PriorityQueue <Node> fifo = new PriorityQueue <Node>();

I am following the conventional add and remove/poll method supplied by the interface. Below is the code for the BFS algorithm.

public static void BFS(Node initial, char [][] grid){
Queue <Node> fifo = new LinkedList <Node>();
ArrayList<Node> explored = new ArrayList<Node>();
int l = 0;
//Make a method to test if there is any dirt remaining on the grid for THIS node
boolean dirtExists = testDirt(initial.dirtCoordinates);
//System.out.println("complete boolean value is: " + dirtExists);
//If no dirt, then we are done
//Test whether there are any more elements in the queue. If not, then done
//Grab the next element in the queue
Node nextNode = fifo.poll();
System.out.println("First element removed " + nextNode.stringBuilder);
dirtExists = true;

dirtExists = false;
List<Node> possibleMoves;
possibleMoves = successor(nextNode, grid);

for(int i=0; i<possibleMoves.size(); i++){
Node temp = possibleMoves.get(i);
System.out.println("About to enter the queue " + temp.stringBuilder);

//Need to make sure this nextNode does not exist in explored OR the fifo already
//Dont worry about this, it still adds new unique nodes to the fifo, i just dont know why its adding it to the head
if(compareNodes(temp, fifo, explored)){
//Then do not add because it is a duplicate
System.out.println("Just got added to the queue " + temp.stringBuilder);
System.out.println("Head of the queue is: " + fifo.peek().stringBuilder);


As Cody from below pointed out

All I was passing the fifo variable into a method in which I was using the poll function. This caused the issue.

So I got rid of the polling I did in the function and just iterated through the queue.

Problem Solved!


Modify your method. Remove poll because it is removing from original list. You can directly use equals method, which you can generate in your Node class.

private static boolean compareNodes(Node currentNode, Queue<Node> fifo, ArrayList<Node> explored){
    boolean exists = false;
        exists = fifo.contains(currentNode);
            //System.out.println("Exists in fifo");

        for(Node n: explored){
                //System.out.println("Exists in explored");
                exists = true;
                //keep on going

    return exists;