Trying to sort a priority queue by one of the stored nodes' values

随声附和 提交于 2019-12-25 03:25:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!