2010-01-24 25 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为您提供的有限工具非常简单!

相关问题