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!
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With