0
    import java.util.*;
    class Huffman  {
        int a;
        public Huffman(int i)
        {
            a = i;
        }               
    }

    class PriorityQueueDemo implements Comparator<Huffman>
    {
        public int compare(Huffman ab, Huffman cd)
        {
            if(ab.a>cd.a)
            {
                return 1;

            }
            return 0;
        }

        public static void main(String[] args)  
        {
            PriorityQueue<Huffman> HuffQueue = new PriorityQueue<Huffman>();

            Huffman ab = new Huffman(10);
            HuffQueue.offer(ab);
            ab = new Huffman(50);
            HuffQueue.offer(ab);
            ab = new Huffman(20);
            HuffQueue.offer(ab);
            ab = new Huffman(60);
            HuffQueue.offer(ab);


            while(HuffQueue.size() > 0)
                   System.out.println(HuffQueue.remove());

            }
    }

以下代码有什么问题!它生成以下异常

Exception in thread "main" java.lang.ClassCastException: Huffman cannot be cast to java.lang.Comparable
    at java.util.PriorityQueue.siftUpComparable(Unknown Source)
    at java.util.PriorityQueue.siftUp(Unknown Source)
    at java.util.PriorityQueue.offer(Unknown Source)
    at PriorityQueueDemo.main(Huffman.java:34)
4

2 回答 2

4

你需要实现Comparable接口

依赖于自然排序的优先级队列也不允许插入不可比较的对象(这样做可能会导致 ClassCastException)。

或者你需要在构造函数中传递比较器

public PriorityQueue(int initialCapacity, Comparator<? super E> comparator)

如下

PriorityQueue<Huffman> HuffQueue = new PriorityQueue<Huffman>(10, new Comparator<Huffman>(){

@Override
public int compare(Huffman ab, Huffman cd){
            if(ab.a>cd.a)
            {
                return 1;

            }
            return 0;
}
});
于 2012-06-15T05:18:58.820 回答
0

异常状态Hufmann类是没有Comparable,没有实现java.util.Comparable,所要求的PriorityQueue。实施ComparableintoHuffman以便可比较并在队列中获得适当的优先级。在http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.htmlComparable中有解释,需要方法实现。compareTo(T o) : int

于 2012-06-15T05:22:30.103 回答