I am sorting my array list int items by using "compareTo(String string);" this method comparing only string but not int values.How I can sort my array list based on integer value.

Here is my code :

 Collections.sort(mAllSpeedsArray, new AllSpeedsComparator());

public class AllSpeedsComparator implements Comparator<AllSpeeds> {

@Override
public int compare(AllSpeeds lhs, AllSpeeds rhs) {
    // TODO Auto-generated method stub      
        return lhs.getSpeed().compareTo(rhs.getSpeed());        
    }
}
有帮助吗?

解决方案 2

How about this

@Override
public int compare(AllSpeeds lhs, AllSpeeds rhs) {
    // TODO Auto-generated method stub      
    int a = Integer.parseInt(lhs.getSpeed());
    int b = Integer.parseInt(rhs.getSpeed());
    return a < b ? 1 : (a == b ? 0 : -1);
}

其他提示

Either make your AllSpeeds data structure return an int (or double, or something else numeric) from getSpeed(), or use Integer.parse(string) on the two strings and then compare the integers.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top