Collections.sort(list, new Comparator<AppEntity>() {
@Override
public int compare(AppEntity lhs, AppEntity rhs) {
if (rhs.isRecommend != lhs.isRecommend) {
return 0; // 💥 錯誤:返回 0 表示「相等」,排序算法視為無序
}
return -1; // 💥 錯誤:固定返回 -1 導致排序不穩定、邏輯錯誤
}
});
compare(a, b) 返回值語義:
Collections.sort(list, (a, b) -> {
// true > false,所以 b 是 true 時返回正數(b 前),a 是 true 時返回負數(a 前)
return Boolean.compare(b.isRecommend, a.isRecommend);
});
Collections.sort(list, new Comparator<AppEntity>() {
@Override
public int compare(AppEntity a, AppEntity b) {
if (a.isRecommend && !b.isRecommend) {
return -1; // a 推薦,b 不推薦 → a 前
} else if (!a.isRecommend && b.isRecommend) {
return 1; // a 不推薦,b 推薦 → b 前
} else {
return 0; // 同樣推薦狀態 → 保持相對順序(穩定排序)
}
}
});
list.sort(Comparator.comparing(AppEntity::isRecommend).reversed());
// isRecommend 為 true 的排在前面
| 場景 | 原代碼返回 | 排序器理解 | 結果 |
|---|---|---|---|
| a=true, b=false | 0 | a == b | 順序不確定,可能不交換 |
| a=false, b=true | 0 | a == b | 順序不確定 |
| a=true, b=true | -1 | a < b | a 排前,但邏輯混亂 |
| a=false, b=false | -1 | a < b | a 排前,違反穩定性 |
Boolean.compare, Integer.compare, Comparator.comparing