gpt4 book ai didi

java - 为什么 PriorityQueue.toString 返回错误的元素顺序?

转载 作者:行者123 更新时间:2023-12-01 16:24:37 27 4
gpt4 key购买 nike

我正在尝试在java中创建一个优先级队列,其中优先级频率最低的节点。然而,我的比较器不工作,输出非常奇怪。我相信我需要改变我的比较器,但我不知道如何改变它。这是我的代码:

public class HuffmanComparator implements Comparator<TreeNodeHuffman> {
public int compare(TreeNodeHuffman p1, TreeNodeHuffman p2) {
if (p1.frequency < p2.frequency) return -1;
if (p1.frequency > p2.frequency) return 1;
return 0;
}
}

public class TreeNodeHuffman {
public static void main(String[] args) {
HuffmanComparator compare = new HuffmanComparator();
TreeNodeHuffman e = new TreeNodeHuffman('e', 12702);
TreeNodeHuffman t = new TreeNodeHuffman('t', 9056);
TreeNodeHuffman a = new TreeNodeHuffman('a', 8167);
TreeNodeHuffman o = new TreeNodeHuffman('o', 7507);
TreeNodeHuffman i = new TreeNodeHuffman('i', 6966);
TreeNodeHuffman n = new TreeNodeHuffman('a', 6749);
TreeNodeHuffman s = new TreeNodeHuffman('s', 6327);
TreeNodeHuffman h = new TreeNodeHuffman('h', 6094);
TreeNodeHuffman r = new TreeNodeHuffman('r', 5987);
TreeNodeHuffman d = new TreeNodeHuffman('d', 4253);
TreeNodeHuffman l = new TreeNodeHuffman('l', 4025);
TreeNodeHuffman c = new TreeNodeHuffman('c', 2782);
TreeNodeHuffman u = new TreeNodeHuffman('u', 2758);
TreeNodeHuffman m = new TreeNodeHuffman('m', 2406);
TreeNodeHuffman w = new TreeNodeHuffman('w', 2360);
TreeNodeHuffman f = new TreeNodeHuffman('f', 2228);
TreeNodeHuffman g = new TreeNodeHuffman('g', 2015);
TreeNodeHuffman y = new TreeNodeHuffman('y', 1974);
TreeNodeHuffman p = new TreeNodeHuffman('p', 1929);
TreeNodeHuffman b = new TreeNodeHuffman('b', 1492);
TreeNodeHuffman v = new TreeNodeHuffman('v', 978);
TreeNodeHuffman k = new TreeNodeHuffman('k', 772);
TreeNodeHuffman j = new TreeNodeHuffman('j', 153);
TreeNodeHuffman x = new TreeNodeHuffman('x', 150);
TreeNodeHuffman q = new TreeNodeHuffman('q', 95);
TreeNodeHuffman z = new TreeNodeHuffman('z', 74);
PriorityQueue<TreeNodeHuffman> queue = new PriorityQueue<TreeNodeHuffman>(26, compare);
queue.add(e);
queue.add(t);
queue.add(a);
queue.add(o);
queue.add(i);
queue.add(n);
queue.add(s);
queue.add(h);
queue.add(r);
queue.add(d);
queue.add(l);
queue.add(c);
queue.add(u);
queue.add(m);
queue.add(w);
queue.add(f);
queue.add(g);
queue.add(y);
queue.add(p);
queue.add(b);
queue.add(v);
queue.add(k);
queue.add(j);
queue.add(x);
queue.add(q);
queue.add(z);
System.out.println(queue);
}
}

输出结果如下:[z、k、q、g、v、x、u、d、f、y、b、m、j、i、c、e、s、o、w、a、r、h、p、t、l ,一个]。

但是,输出应该是[z, q, x, j, k, v, b........]。

最佳答案

您需要逐一轮询PriorityQueue中的项目。 toString 不会这样做。

因此,不要使用 System.out.println(queue); 这样做:

while(!queue.isEmpty()) {
System.out.println(queue.poll());
}

原因是 PriorityQueue 内部永远不会完全排序,请查看堆的工作原理以了解更多详细信息。从中轮询项目会在调用期间修复堆,因此它应该按排序顺序输出元素。

关于java - 为什么 PriorityQueue.toString 返回错误的元素顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62174536/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com