我正在尝试使用比较器按时间和点对列表进行排序,时间更重要,如果对象具有相同的时间,则比较点。
这是我尝试过的,但结果并不完全符合我想要的方式。
我比较错误吗?
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/