英文:
Why does Collections not sorting objects properly using timestamp?
问题
从 Firebase 实时数据库中获取的对象放入 ArrayList<PostModel> 后,使用 Collections.sort() 方法无法正确排序。我获取的 ArrayList 中总共有 17 个对象(帖子),其中 2 个对象是 1 个月前发布的,其余 15 个在一个月内发布。集合能够正确排序这 15 个对象,但这 2 个对象在排序时被放在了这 15 个对象之前。
我想按时间戳的升序对这些对象进行排序,以便先显示较新的帖子,后显示较旧的帖子。但是非常旧的帖子(超过1个月)在排序时被放在前面。
我为 Firebase 创建了以下的 PostModel 类结构:
PostModel 类:
public class PostModel {
public String title, description;
public long timestamp;
public PostModel() {}
public PostModel(String title, String description, long timestamp) {
this.title = title;
this.description = description;
this.timestamp = timestamp;
}
}
我在以上的类对象中传递了时间戳以便插入,使用以下方式进行排序:
Collections.sort(postsObjs, new Comparator<PostModel>() {
@Override
public int compare(PostModel o1, PostModel o2) {
return (int) (o2.timestamp - o1.timestamp);
}
});
请帮我解决正确排序对象的问题。谢谢。
编辑: 我的 ArrayList 中有 17 个对象,而不是 7 个,其余内容保持不变。
英文:
When I have fetched objects from firebase realtime database into ArrayList<PostModel> then they are not sorted properly using Collections.sort() method. I have total 17 objects(posts) in my fetched ArrayList in which 2 objects are 1 month ago and rest 15 are under a month. Collection sorts properly these 15 objects but these 2 objects are added before 15 objects in sorting.
I am sorting these objects into ascending order of timestamp to show newer posts first and older at last. But very old posts (more than 1 month) are added before on sorting.
I have following PostModel class structure for Firebase
PostModel Class:
public class PostModel {
public String title,description;
public long timestamp;
public PostModel(){}
public PostModel(String title, String description,long timestamp) {
this.title = title;
this.description = description;
this.timestamp = timestamp;
}
}
I have passed timestamp into above class objects for insertion as System.currentTimeMillis(); and sorted using following way.
Collections.sort(postsObjs, new Comparator<PostModel>() {
@Override
public int compare(PostModel o1, PostModel o2) {
return (int) (o2.timestamp - o1.timestamp);
}
});
Help me to sort my objects properly. Thanks
Edit: I have 17 objects in my ArrayList instead of 7 and rest is same
答案1
得分: 0
一个比较方法应该返回-1、0或1;
0:如果(x==y)
-1:如果(x < y)
1:如果(x > y)
尝试这样做:
return Long.compare(o2.timestamp - o1.timestamp);
英文:
A compare method should return -1,0 or 1;
0: if (x==y)
-1: if (x < y)
1: if (x > y)
try this:
return Long.compare(o2.timestamp - o1.timestamp);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论