Question

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());        
    }
}
Was it helpful?

Solution 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);
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top