排序数组顶部包含"pinned"对象的对象列表每次执行的行为都不同



所以我试图在Android的回收视图中显示组列表。组是具有少量值的自定义对象(Group(,存储在公共静态数组列表(allGroups(中。

我有一种方法可以根据它们的";时间";值,这是以毫秒为单位的时间。

排序方法:

public static ArrayList<Group> sort(ArrayList<Group> list) {
list.sort(Comparator.comparing(Group::getTime));
Collections.reverse(list);
ArrayList<Group> newSort = new ArrayList<>();
for(Group g: list) {
if(g.isPinned()) {
newSort.add(g);
}
}
for(Group g: list) {
if(!g.isPinned()) {
newSort.add(g);
}
}
list.clear();
return newSort;
}

当我第一次运行该应用程序时,它运行良好,可以完美地按pin和日期对我的组进行排序,但每当我使用下面的方法添加组时,它只按日期对其进行排序

allGroups.add(new Group(
new BigInteger(130, new java.util.Random()).toString(32),
"PB",
(long) (Math.random() * 1649157582577L),
new BigInteger(260, new java.util.Random()).toString(32)
).makePinned(false));
allGroups = sort(allGroups);
groupsAdapter.notifyDataSetChanged();

我不知道是什么原因造成的,这对我来说毫无意义。

编辑:

makePinned:的实现

public Group makePinned(boolean pinned) {
this.pinned = pinned;
return this;
}

集团建设单位:

public Group(String name, String logo, long time, String message) {
this.id = groupAmount + 1;
this.name = name;
this.logo = logo;
this.time = time;
this.message = message;
}

您的">找到答案";是不正确的,因为您的第二个排序语句:

list.sort(Comparator.comparing(Group::isPinned));

完全覆盖第一个排序。好吧,对于你的测试样本,它可能会给出你想要的结果(巧合的是,保留了第一个排序的一些顺序(,但这是不可依赖的未定义行为。

你可能想要的是更好的实现方式:

allGroups.sort(Comparator.comparing(Group::isPinned)
.thenComparing(Group::getTime).reversed());

这是先按isPined显式排序,然后按相反顺序按getTime显式排序。明确是好的。

我写了一个示例程序,可以在这里使用:在线Java编译器,它是:

  1. 根据您的问题进行排序
  2. 随机排列列表(即取消排序(
  3. 按以上排序

最新更新