问题
So I'm new to priority queues. In an algorithm I'm trying to implement, I want to sort a priority queue according to the stored nodes' functionValue. I don't understand how the priority queue will know to sort the nodes by that value, as opposed to one of the other eight instance variables of my node objects. I'm pretty sure I define a Comparator object to define the comparison/ sorting rules, but I can't make heads or tails of the Oracle class library for Comparator.
Here are the properties of my Node Class
public class Node{
public char label; //Holds char for the Move used; U, D, L, R
public boolean visited = false;
public State nodeState; //Each node holds a State object
int depth;
int heuristicCount;
int functionCount; <--- This is the property I want the priority queue to sort by.
.
.
.
回答1:
Comparator
is a pretty simple interface. What's your difficulty with it? The key bit is the compare method. You simply implement that to compare two instances of your class. Something like:
public class NodeComparator implements Comparator<Node> {
public int compare(Node a, Node b) {
Integer aCount = a.getFunctionCount();
Integer bCount = b.getFunctionCount();
return a.compareTo(b);
}
}
来源:https://stackoverflow.com/questions/12761356/trying-to-sort-a-priority-queue-by-one-of-the-stored-nodes-values