I'm building a huffman tree for a class currently. After reviewing my available options I decided to go the priority queue method. However, when I try to run the below code I get a ClassCastException on TreeNode (on the first pq.offer line).
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();
}
I know it's not a comparable class, however, CharFreq is, and my question is am I able to fix my code so it avoids this casting problem?