title: Using a priority queue on a non-comparable object with a comparable object inside it
body: <p>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).</p>
  
  <pre><code>public static TreeNode&lt;CharFreq&gt; buildTree(ArrayList&lt;TreeNode&lt;CharFreq&gt;&gt; trees) throws IOException {
  
     PriorityQueue&lt;TreeNode&lt;CharFreq&gt;&gt; pq = new PriorityQueue&lt;TreeNode&lt;CharFreq&gt;&gt;();
  
     for (int i = 0; i &lt; trees.size(); i++) {
       if (trees.get(i).getItem().getFreq() &gt; 0) {
         pq.offer(new TreeNode&lt;CharFreq&gt;(new CharFreq(trees.get(i).getItem().getChar(), trees.get(i).getItem().getFreq())));
       }
     }  
  
     while (pq.size() &gt; 1) {    
         TreeNode&lt;CharFreq&gt; leftNode = pq.poll();
         TreeNode&lt;CharFreq&gt; rightNode = pq.poll();
         TreeNode&lt;CharFreq&gt; parentNode = new TreeNode&lt;CharFreq&gt;(new CharFreq('\u0000', ((leftNode.getItem().getFreq()) + (rightNode.getItem().getFreq()))), leftNode, rightNode);
     }  
  
     return pq.poll();
  
  }
  </code></pre>
  
  <p>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? </p>