Вопрос

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