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?
4 Answers
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.
2 Comments
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...compareTo method, but that is not a Comparator.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));
Comparator, or implementComparable<Node>and write acompareTo(). If you were hoping that Java would automatically notice that you have oneintfield and generate the comparator itself--sorry, no.