2010-01-24 57 views
2

我想讓以下代碼在Java ME/J2ME環境中工作。請幫助:根據輸入值(不是密鑰)對散列表進行排序

Hashtable <Activity, Float>scores = new Hashtable<Activity, Float>(); 
    scores.put(act1, 0.3); 
    scores.put(act2, 0.5); 
    scores.put(act3, 0.4); 
    scores.put(act5, 0.3); 


    Vector v = new Vector(scores.entrySet()); 
    Collections.sort(v); //error is related to this line 
    Iterator it = v.iterator(); 

    int cnt = 0; 
    Activity key; 
    Float value; 

    while(it.hasNext()){ 

     cnt++; 
     Map.Entry e=(Map.Entry)it.next(); 

     key = (Activity)e.getKey(); 
     value = (Float)e.getValue(); 

     System.out.println(key+", "+value); 
    } 

它不工作,我得到的錯誤:

Exception in thread "main" java.lang.ClassCastException: java.util.Hashtable$Entry cannot be cast to java.lang.Comparable This points to the line that I've indicated with a comment in the code.

請幫幫忙,並且要記住,我使用J2ME!

回答

0

entrySet方法不返回散列表中的值,它返回鍵值對。如果你想要的值,你應該使用values方法。

如果您想要鍵值對,但僅對值進行排序,則必須爲鍵值對實現Comparator,以比較兩對值的值,並使用sort方法的過載Comparator以及列表。

4

你已經得到的代碼不在有效的J2ME附近,它是全脂(J2SE)Java; J2ME目前沒有泛型,或Collections類或Comparable接口 - 檢查J2ME的組件MIDP 2CLDC 1.1的JavaDoc。你的錯誤提到了這些,所以絕對不是來自J2ME,這表明你可能在你的項目設置中做了一些根本性的錯誤。

如果你確實想在J2ME中做到這一點,你需要自己編寫一個排序函數,因爲據我所知,不存在這樣的事情。 Bubblesort最容易編寫,因爲您可以輕鬆訪問哈希表的順序成員的唯一方法是通過枚舉(通過scores.keys()和scores.values())。假設你想在基礎上,他們正在與相關的分數(浮點)升序排列的活動排序,你想要的東西,如:

boolean fixedPoint = false; 
while (!fixedPoint) 
{ 
    fixedPoint = true; 

    Enumeration e = scores.keys();  
    if (!e.hasMoreElements()) return; 
    Object previousKey = e.nextElement(); 

    while (e.hasMoreElements()) { 
    Object currentKey = e.nextElement(); 
    if ((Float) scores.get(currentKey) > (Float) scores.get(previousKey)) { 
     swap(currentKey, previousKey); 
     fixedPoint = false; 
    } 
    previousKey = currentKey; 
    } 
} 

此外,地方你需要編寫一個交換兩個交換功能哈希表的元素在給定密鑰時。值得注意的是,這不是最快的實施方式 - 如果您期望擁有大的大名單,泡泡排序不會很好。另一方面,J2ME爲您提供的有限工具非常簡單!

相關問題