[英]Sorting list of custom objects wrt a property in android studio (API level problem)
我想在android中根據其一個屬性(變量類型為“long”)按降序對自定義對象列表進行排序。 為此,我使用了 Collections Comparator 但我的問題是它說“Long.compare 調用需要 API 級別 19(當前最小值為 16)” 有沒有其他方法可以處理這個問題? (代碼在我的虛擬設備上完美運行,沒有錯誤,但我希望它在 API 級別低於 19 的設備上運行)
我的排序代碼是:
// Sort the news according to their last update time (show the latest on top)
Collections.sort(news, new Comparator<NewsItem>() {
@Override
public int compare(NewsItem newsItem1, NewsItem newsItem2) {
return Long.compare(newsItem2.getUpdateTime(), newsItem1.getUpdateTime());
}
});
我的自定義對象是具有五個屬性的 NewsItem,我想將列表 wrt 排序為 Long 類型的 UpdateTime 屬性。
您可以為時間創建Long
對象並直接比較它們:
Collections.sort(news, new Comparator<NewsItem>() {
@Override
public int compare(NewsItem newsItem1, NewsItem newsItem2) {
return Long.valueOf(newsItem2.getUpdateTime()).compareTo(
Long.valueOf(newsItem1.getUpdateTime()));
}
});
附帶說明 - API 級別 16 已經過時了,您可能需要考慮升級您的要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.