Sorting a hashtable based on its entry value (not the key)
I want to get the following code to work in the Java ME / J2ME environment. Please help:
Hashtable <Activity, Float>scores = new Hashtable<Activity, Float>();
scores.put(act1, 0.3);
scores.p开发者_开发技巧ut(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);
}
It doesn't work, I get the error:
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.
Please help, and bear in mind that I'm using j2me!
The code you've got isn't anywhere near valid J2ME, it's full fat (J2SE) java; J2ME doesn't currently have generics, or a Collections class or a Comparable interface - check for JavaDoc for MIDP 2 and CLDC 1.1, the components of J2ME. Your error mentions those, so definitely didn't come from J2ME, which suggests you might be doing something fundamental wrong in your project setup?
If you do want to do this in J2ME you need to write a sort function yourself, because as far as I can tell no such thing exists. Bubblesort will be easiest to write, since the only way you can easily access sequential members of the hashtable is through Enumerations (via scores.keys() and scores.values()). Assuming you want to sort your activities in ascending order based on the scores (floats) they're associated with, you want something like:
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;
}
}
Also, somewhere you'll need to write a swap function that swaps two elements of the hashtable when given their keys. Worth noting this is NOT the quickest possible implementation -- bubble sort will not be good if you expect to have big big lists. On the other hand, it is very easy with the limited tools that J2ME gives you!
The entrySet
method doesn't return the values in the hash table, it returns the key-value pairs. If you want the values you should use the values
method instead.
If you want the key-value pairs but sort them only on the value, you have to implement a Comparator
for the key-value pairs that compares the values of two pairs, and use the overload of the sort
method that takes the Comparator
along with the list.
精彩评论