1

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?

sammy333
  • 1,384
  • 6
  • 21
  • 39
  • You will either need to write a `Comparator`, or implement `Comparable` and write a `compareTo()`. If you were hoping that Java would automatically notice that you have one `int` field and generate the comparator itself--sorry, no. – ajb Sep 19 '14 at 20:18

4 Answers4

3

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) {
        ...
    }
}
ChoChoPK
  • 69
  • 1
  • 5
3

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.

sol4me
  • 15,233
  • 5
  • 34
  • 34
0

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • That does require a `compareTo` method be written. My suspicion is that the OP wanted to know if Java would automatically make classes with one `int` field comparable by using the built-in comparison on the `int`, and the answer to that is no. But I should be wary of trying to read people's minds... – ajb Sep 19 '14 at 20:15
  • @ajb Yes, it does require a `compareTo` method, but that is not a `Comparator`. – rgettman Sep 19 '14 at 20:19
0

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));
mavenHawk
  • 51
  • 5