I am trying to write an algorithm which utilizes a min-priority queue, so I looked around on google and found the PriorityQueue. It seems that in order to use it, though, I
As you can see here (the JSE Comparator JavaDoc page),
the Comparator
interface has a generic "parameter"
describing the type
for which this comparator is designed.
The PriorityQueue is similar.
So,
if you create a PriorityQueue<Node1>
,
you can create a Comparator<Node1>
as follows:
public class distComparator implements Comparator<Node1> {
@Override
public int compare(Node1 x, Node1 y){
return x.dist - y.dist;
}
}
You need to implement Comparator<Node1>
:
public class distComparator implements Comparator<Node1> {
^^^^^^^
Without this, you are implementing Comparator<Object>
, which isn't what you want (it can be made to work, but isn't worth the hassle).
The rest of the code in your question is fine, provided Node1
has an accessible member called dist
.
Note that if you are using Java 7, the entire body of the method can be replaced with
return Integer.compare(x.dist, y.dist);
(replace Integer
with Double
etc, depending on the type of Node1.dist
.)