Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 771
Bharat Avatar asked Mar 31 '10 18:03

Bharat


People also ask

Can we use comparator in priority queue?

The comparator() method of PriorityQueue() class returns the comparator that is used to order the elements of this queue, or returns null if the elements of this queue are sorted according to natural ordering.

How does comparator work in Java priority queue?

comparator() method shares an important function of setting and returning the comparator that can be used to order the elements in a PriorityQueue. The method returns a null value if the queue follows the natural ordering pattern of the elements.

What is PriorityQueue Java?

A priority queue in Java is a special type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation.

How do I avoid duplicates in priority queue?

A PriorityQueue in Java does not have any restriction with regard to duplicate elements. If you want to ensure that two identical items are never present in the priority queue at the same time the simplest way would be to maintain a separate Set in parallel with the priority queue.


1 Answers

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.

like image 116
Yuval Adam Avatar answered Oct 05 '22 11:10

Yuval Adam