Search code examples
javapriority-queue

Java Priority Queue with a custom anonymous comparator


Forgive me if this is a tried question, but I'm having a little difficulty figuring it out.

I currently have a class Node, and each 'node' is a square in a maze. I'm trying to implement the A* algorithm, so each of these nodes will have an f-cost (int) data member inside of it. I was wondering if there's a way that I can create a priority queue of these nodes, and set up the f-cost variable as the comparator?

I've looked at examples online, but all I can find are String priority queues. Can I implement Comparator for the Node class? Would this allow me to access the data member stored inside it?

Many Thanks!


Solution

  • Absolutely.

    You can use a PriorityQueue based on an anonymous Comparator passed to the constructor:

    int initCapacity = 10;
    PriorityQueue<Node> pq = new PriorityQueue<Node>(initCapacity, new Comparator<Node>() {
        public int compare(Node n1, Node n2) {
            // compare n1 and n2
        }
    });
    // use pq as you would use any PriorityQueue
    

    If your Node class already implements Comparable you don't even need to define a new Comparator, as that order will be used by default. Barring any other method, the natural ordering between objects will be used.