我想根据 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,我想根据 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 已经过时,您可能需要考虑升级您的要求。
关于java - 在 android studio 中排序自定义对象的属性列表(API 级问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52469811/