集合比较器报错java.lang.IllegalArgumentException: Comparison method violates its general contract!_比较器

Collections.sort(listMonthlyUsage, new Comparator<MonthlyUsageDto>() { //按照元素从小到大排序
@Override
public int compare(MonthlyUsageDto o1, MonthlyUsageDto o2) {
if(o1.getCstId() > o2.getCstId()) return 1;
else return -1;
// return o1.getCstId() - o2.getCstId();
}
});

上面代码报错都是因为我们比较器不够严谨,只有返回1和-1,米有返回0。将代码改为下面就正常了:

Collections.sort(listMonthlyUsage, new Comparator<MonthlyUsageDto>() { //按照元素从小到大排序
@Override
public int compare(MonthlyUsageDto o1, MonthlyUsageDto o2) {
if(o1.getCstId() > o2.getCstId()) return 1;
else if (o1.getCstId() == o2.getCstId()) return 0;
else return -1;
// return o1.getCstId() - o2.getCstId();
}
});