为什么 Collections 不使用时间戳正确排序对象?
Why does Collections not sorting objects properly using timestamp?
当我将对象从 firebase 实时数据库提取到 ArrayList 中时,它们没有使用 Collections.sort() 方法正确排序。我在获取的 ArrayList 中共有 17 个对象(帖子),其中 2 个对象是 1 个月前的,剩下的 15不到一个月。集合正确排序这些 15 个对象,但这些 2 个对象在排序中添加到 15 个对象之前。
我将这些对象按时间戳的升序排序,以便先显示较新的帖子,最后显示较旧的帖子。但是在排序之前添加了非常旧的帖子(超过1个月)。
我有以下 PostModel class Firebase 结构
后模型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;
}
}
我已将时间戳传递到上面的 class 个对象中以插入 System.currentTimeMillis(); 并使用以下方式排序。
Collections.sort(postsObjs, new Comparator<PostModel>() {
@Override
public int compare(PostModel o1, PostModel o2) {
return (int) (o2.timestamp - o1.timestamp);
}
});
帮我把我的物品正确分类。谢谢
编辑: 我的 ArrayList 中有 17 个对象,而不是 7 个,其余相同
比较方法应该 return -1,0 或 1;
0: 如果 (x==y)
-1: 如果 (x < y)
1: 如果 (x > y)
试试这个:
return Long.compare(o2.timestamp - o1.timestamp);
当我将对象从 firebase 实时数据库提取到 ArrayList 中时,它们没有使用 Collections.sort() 方法正确排序。我在获取的 ArrayList 中共有 17 个对象(帖子),其中 2 个对象是 1 个月前的,剩下的 15不到一个月。集合正确排序这些 15 个对象,但这些 2 个对象在排序中添加到 15 个对象之前。
我将这些对象按时间戳的升序排序,以便先显示较新的帖子,最后显示较旧的帖子。但是在排序之前添加了非常旧的帖子(超过1个月)。
我有以下 PostModel class Firebase 结构
后模型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;
}
}
我已将时间戳传递到上面的 class 个对象中以插入 System.currentTimeMillis(); 并使用以下方式排序。
Collections.sort(postsObjs, new Comparator<PostModel>() {
@Override
public int compare(PostModel o1, PostModel o2) {
return (int) (o2.timestamp - o1.timestamp);
}
});
帮我把我的物品正确分类。谢谢
编辑: 我的 ArrayList 中有 17 个对象,而不是 7 个,其余相同
比较方法应该 return -1,0 或 1;
0: 如果 (x==y)
-1: 如果 (x < y)
1: 如果 (x > y)
试试这个:
return Long.compare(o2.timestamp - o1.timestamp);