简体   繁体   English

在Java中为PriorityQueue(node)设置比较器

[英]setting a comparator for PriorityQueue(node) in Java

If I have a node with two data variables. 如果我有一个带有两个数据变量的节点。

Say

class HuffNode{
public char iData;
public int frequency;
public HuffNode leftChild;
public HuffNode rightChild;
// ---------------------------------------------------------
HuffNode(char d){
    this.iData = d;
    this.frequency = 0;
}
}

Then, I want to put them in ascending order into a priority que by each Node's frequency. 然后,我想按每个节点的频率将它们按升序排列为优先级。

PriorityQueue<HuffNode> q = new PriorityQueue<HuffNode>();
    Set<Character>keys = map.keySet(); //iterator
    Iterator<Character> it = keys.iterator();
    while(it.hasNext()){
        char key = it.next();
        HuffNode node = new HuffNode(key);
        node.frequency = map.get(key);
        q.add()// want to add by frequency
    }

If I just add the nodes into the que, I think the nodes will end up in an alphabetical order. 如果仅将节点添加到队列中,我认为节点将以字母顺序结束。 How can I change the comparator to the frequency ? 如何将比较器更改为频率?

thank you in advance. 先感谢您。

Pass a Comparator as a constructor parameter , eg 将Comparator作为构造函数参数传递 ,例如

new PriorityQueue<>(
    initialCapacity,
    new Comparator<HuffNode>() {
      @Override public int compare(HuffNode a, HuffNode b) {
        return Integer.compare(a.frequency, b.frequency);
      }
    });

Note that you don't really want the thing you are using to order the nodes to be mutable, especially if it is public - if you were to change the frequency value, it wouldn't automatically reorder in the queue. 请注意,您实际上并不希望用来排序节点的变量是可变的,尤其是在公共节点上-如果要更改频率值,它将不会在队列中自动重新排序。

You'd be well-served making as many fields as possible final . final字段尽可能多,这final

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM