簡體   English   中英

如何在Android中根據Integer大小對arrayList進行排序?

[英]How to sort arrayList according to Integer size in android?

我正在使用“ compareTo(String string);”對數組列表int項進行排序 此方法僅比較字符串而不是int值。如何根據整數值對數組列表進行排序。

這是我的代碼:

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

使您的AllSpeeds數據結構從getSpeed()返回一個int (或double或其他數字getSpeed() ,或者對兩個字符串使用Integer.parse(string) ,然后比較整數。

這個怎么樣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM