gpt4 book ai didi

java - 如何连续两次使用比较器?

转载 作者:搜寻专家 更新时间:2023-11-01 07:54:48 24 4
gpt4 key购买 nike

我正在尝试使用比较器按时间和点对列表进行排序,时间更重要,如果对象具有相同的时间,则比较点。

这是我尝试过的方法,但结果并不是我想要的那样。

我是不是比较错了?

Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
public int compare(DatabaseGuard p1, DatabaseGuard p2) {
int endShiftInt = (int) p1.getEndShift()/1000;
int endShiftInt2 = (int) p2.getEndShift()/1000;

if(endShiftInt == endShiftInt2) {
Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
public int compare(DatabaseGuard p1, DatabaseGuard p2) {
return Integer.valueOf(p1.getPoints()).compareTo(p2.getPoints());
}
});
}
return Integer.valueOf(endShiftInt).compareTo(endShiftInt2);
}
});

我也试过这个:

Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
public int compare(DatabaseGuard p1, DatabaseGuard p2) {
return Integer.valueOf(p1.getPoints()).compareTo(p2.getPoints());
}
});

//sortUsers in order of last Time They Guarded, those with a higher number is more recent, then lower numbers first
Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {
public int compare(DatabaseGuard p1, DatabaseGuard p2) {
int endShiftInt = (int) p1.getEndShift()/1000;
int endShiftInt2 = (int) p2.getEndShift()/1000;

return Integer.valueOf(endShiftInt).compareTo(endShiftInt2);
}
});

最佳答案

比那简单多了。使用类似的东西:

    Collections.sort(onlyGuardsStatArray, new Comparator<DatabaseGuard>() {

public int compare(DatabaseGuard p1, DatabaseGuard p2) {
int endShiftInt = (int) p1.getEndShift() / 1000;
int endShiftInt2 = (int) p2.getEndShift() / 1000;

if (endShiftInt == endShiftInt2) {
return Integer.valueOf(p1.getPoints()).compareTo(p2.getPoints());
}
return Integer.valueOf(endShiftInt).compareTo(endShiftInt2);
}
}
);

本质上 - 如果第一个属性相同,则应返回第二个属性之间的差异。

关于java - 如何连续两次使用比较器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29540836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com