sammy333
sammy333

Reputation: 1445

Can I use Priority Queue in Java without implementing a comparator?

If I want to create priority queue of nodes, and each node has only one field (i.e. int val) do I have to write a comparator for the priority queue?

Upvotes: 1

Views: 2296

Answers (4)

mavenHawk
mavenHawk

Reputation: 51

You don't necessarily need to implement Comparator in the Node class. You can use lambda expressions as detailed in the first part of this answer. I will modify that answer to fit into your question. For this to work you will have to create a getter method for the field that you have. Assuming that method is called "getVal()" This should work without needing to implement Comparator.

PriorityQueue<Node> pq=
            new PriorityQueue<Node>(Comparator.comparing(Node::getVal));

Upvotes: 0

sol4me
sol4me

Reputation: 15698

The elements of the priority queue are ordered according to their natural ordering, or by a Comparator . If you don't want to use Comparator then implement Comparable in your Node class.

Upvotes: 3

ChoChoPK
ChoChoPK

Reputation: 69

Yes. Assuming your Node class is your custom class, Java does not know how to compare two Nodes even if there's but one field in it. Therefore, you will need to do

class Node implements Comparable<Node> {
    @Override
    public compareTo(Node other) {
        ...
    }
}

Upvotes: 3

rgettman
rgettman

Reputation: 178263

No Comparator necessary. You can create a PriorityQueue that relies on a class's "natural ordering".

Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering.

That links to Comparable. Make your Node class implement Comparable<Node>. Then you can use a PriorityQueue without a Comparator.

Upvotes: 0

Related Questions