gpt4 book ai didi

java - 对内部有可比较对象的不可比较对象使用优先级队列

转载 作者:行者123 更新时间:2023-12-01 15:07:13 25 4
gpt4 key购买 nike

我目前正在为一个类(class)构建一棵霍夫曼树。在查看了可用选项后,我决定采用优先队列方法。但是,当我尝试运行以下代码时,我在 TreeNode 上收到 ClassCastException(在第一个 pq.offer 行上)。

public static TreeNode<CharFreq> buildTree(ArrayList<TreeNode<CharFreq>> trees) throws IOException {

PriorityQueue<TreeNode<CharFreq>> pq = new PriorityQueue<TreeNode<CharFreq>>();

for (int i = 0; i < trees.size(); i++) {
if (trees.get(i).getItem().getFreq() > 0) {
pq.offer(new TreeNode<CharFreq>(new CharFreq(trees.get(i).getItem().getChar(), trees.get(i).getItem().getFreq())));
}
}

while (pq.size() > 1) {
TreeNode<CharFreq> leftNode = pq.poll();
TreeNode<CharFreq> rightNode = pq.poll();
TreeNode<CharFreq> parentNode = new TreeNode<CharFreq>(new CharFreq('\u0000', ((leftNode.getItem().getFreq()) + (rightNode.getItem().getFreq()))), leftNode, rightNode);
}

return pq.poll();

}

我知道它不是一个可比较的类,但是 CharFreq 是,我的问题是我是否能够修复我的代码,从而避免此转换问题?

最佳答案

您可以创建自定义比较器:Comparator<TreeNode<CharFreq>>并在创建 PriorityQueue 时使用它:

http://docs.oracle.com/javase/6/docs/api/java/util/PriorityQueue.html#PriorityQueue(int ,java.util.Comparator)

Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator

使用anonymous class概念,你可以有这样的代码:

public static TreeNode<CharFreq> buildTree(ArrayList<TreeNode<CharFreq>> trees)
throws IOException {
Comparator<TreeNode<CharFreq>> comparator = new Comparator<TreeNode<CharFreq>>() {

//basic implementation, you must use your own!
public int compare(TreeNode<CharFreq> node1, TreeNode<CharFreq> node2) {
return node1.data.compareTo(node2.data);
}
};
PriorityQueue<TreeNode<CharFreq>> pq = new PriorityQueue<TreeNode<CharFreq>>(10, comparator);
//the rest of your code...
}

请注意,使用这种方式意味着您必须创建自定义 Comparator<TreeNode<YourClass>>每次您需要创建 PriorityQueue<TreeNode<YourClass>> .

关于java - 对内部有可比较对象的不可比较对象使用优先级队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12813801/

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