我让用户在Collections.sort上崩溃,而在我的onw测试中,以下代码永远不会崩溃:
Collections.sort(spinnerAreaArray, new Comparator<tarifdata>() {
@Override
public int compare(tarifdata s1, tarifdata s2) {
if (s1.rating > 0 && s2.rating > 0) {
return s1.rating >= s2.rating ? 0 : 1;
}
//one or 0 has a rating
if (s1.rating > 0) return 0;
//now maybe only 2 has a rating
if (s2.rating > 0) return 1;
//noone has a rating
return s1.area_desc.compareToIgnoreCase(s2.area_desc);
}
}
);
如果对象s1和s2都没有设置评级值,我需要按字母顺序排序。 我已经在SO中读到了这个错误,但仍然无法弄清楚为什么会崩溃。
答案 0 :(得分:0)
数学比较具有以下规则,比较器也需要这些规则。
该错误意味着某些内容违反了其中一条规则。当且仅当它们相等时,您应该返回0。改变这样的代码。
Collections.sort(spinnerAreaArray, new Comparator<tarifdata>() {
@Override
public int compare(tarifdata s1, tarifdata s2) {
if (s1.rating > 0 && s2.rating > 0) {
return s1.rating >= s2.rating ? -1 : 1;
}
//one or 0 has a rating
if (s1.rating > 0) return -1;
//now maybe only 2 has a rating
if (s2.rating > 0) return 1;
//noone has a rating
return s1.area_desc.compareToIgnoreCase(s2.area_desc);
}
}
);