简体   繁体   English

android studio 中自定义对象的排序列表(API 级别问题)

[英]Sorting list of custom objects wrt a property in android studio (API level problem)

I want to sort a list of custom objects in descending order with respect to its one property (with a variable type "long") in android.我想在android中根据其一个属性(变量类型为“long”)按降序对自定义对象列表进行排序。 For this, I used Collections Comparator but my problem is it says "Long.compare call requires API level 19 (current min is 16)" Is there any alternative way to handle this?为此,我使用了 Collections Comparator 但我的问题是它说“Long.compare 调用需要 API 级别 19(当前最小值为 16)” 有没有其他方法可以处理这个问题? (The code runs perfectly on my virtual device it gives no error but I want it to run on devices with API level below 19) (代码在我的虚拟设备上完美运行,没有错误,但我希望它在 API 级别低于 19 的设备上运行)

My sorting code is:我的排序代码是:

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

my custom object is NewsItem with five attributes and I want to sort the list wrt to the UpdateTime attribute which is of the Long type.我的自定义对象是具有五个属性的 NewsItem,我想将列表 wrt 排序为 Long 类型的 UpdateTime 属性。

You could create Long objects for the times and compare them directly:您可以为时间创建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()));
    }
});

As a side note - API level 16 is quite outdated, and you may want to consider upgrading your requirements.附带说明 - API 级别 16 已经过时了,您可能需要考虑升级您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM