implementation - Implementing Java Comparator -
i trying write algorithm utilizes min-priority queue, looked around on google , found priorityqueue. seems in order use it, though, going need tell how want prioritize, , way comparator (i want compare specific data fields of "node1" objects). more googling presented idea of creating new comparator implements comparator overrides compare method. trying (and other variations of well):
import java.util.comparator; public class distcomparator implements comparator { @override public int compare(node1 x, node1 y){ if(x.dist<y.dist){ return -1; } if(x.dist>y.dist){ return 1; } return 0; } }
the compiler protests on several grounds, 1 of haven't over-ridden comparator class (which says abstract)
error: distcomparator not abstract , not override abstract method compare(object,object) in comparator
i have switched "compare(object x, object y)", takes care of issue. @ point though compiler complains can't find "dist" variable in x or y--which makes sense, since part of node1 class, not object class.
so how supposed work? should have type object
, apparently, how direct correct variable?
you need implement comparator<node1>
:
public class distcomparator implements comparator<node1> { ^^^^^^^
without this, implementing comparator<object>
, isn't want (it can made work, isn't worth hassle).
the rest of code in question fine, provided node1
has accessible member called dist
.
note if using java 7, entire body of method can replaced with
return integer.compare(x.dist, y.dist);
(replace integer
double
etc, depending on type of node1.dist
.)
Comments
Post a Comment