2013-08-17 64 views
-1

我遇到以下問題 線程「main」中的異常java.lang.ClassCastException:java.lang.ref.SoftReference不能轉換爲java。 lang.Comparablejava.lang.ref.SoftReference不能轉換爲java.lang.Comparable

代碼如下。 謝謝你的幫助!類元素的

PriorityQueue<SoftReference<Element<K, V>>> heap; 
heap.add(new SoftReference<Element<K, V>>(newElement)); 

定義如下

class Element<K, V> implements Comparable<Element<K, V>>{ 
     long timeStamp; 
    K key; 
    V val; 
    @Override 
    public int compareTo(Element<K, V> o) { 
    return new Long(timeStamp).compareTo(o.timeStamp); 
    } 
    Element(long ts, K key, V val){ 
     this.timeStamp = ts; 
     this.key = key; 
     this.val = val; 
     } 
} 
+1

當然,參考文獻不會實現可比較的。參考指向什麼並不重要,它是PriorityQueue想要比較的引用,而不是引用的元素。你的設計是不可能的。 – Durandal

回答

1

沒有定製Comparator預計其元件以實現Comparable創建的PriorityQueue,和SoftReference沒有。嘗試使用自定義Comparator創建您的PriorityQueue,可以比較SoftReference s。

+0

非常感謝!這對我很好。這是代碼。歡迎任何其他意見。 '類SoftReferenceComparator 實現比較器> { \t @Override \t公衆詮釋比較(SoftReference的 O1,SoftReference的 O2){ \t \t返回o1.get()。的compareTo(o2.get ()); (sizeLimit,new SoftReferenceComparator >());''Heap = new PriorityQueue >>(sizeLimit,new SoftReferenceComparator > – user2692465

相關問題