Pergunta

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());        
    }
}
Foi útil?

Solução 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);
}

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top