在之前项目中有根据学年的list进行排序的需求,之前在本地运行没有问题,在集成之后,数据库数据改变了之后报错:
Exception in thread"main" java.lang.IllegalArgumentException: Comparison
method violates itsgeneral contract!
比较方法违反了契约。代码中是用的Collections.sort()方法:
public void listSortGrade(List<Map<Serializable, Serializable>> institutionList) throws Exception {
// resultList是需要排序的list,其内放的是Map
// 返回的结果集
Collections.sort(institutionList, new Comparator<Map<Serializable, Serializable>>() {
public int compare(Map<Serializable, Serializable> o1, Map<Serializable, Serializable> o2) {
// o1,o2是list中的Map,可以在其内取得值,按其排序,此例为升序,s1和s2是排序字段值
String s1 = (String) o1.get("gradeName");
String s2 = (String) o2.get("gradeName");
return s1.compareTo(s2)>0?1:-1;
}
});
}
然后Conllections.sort方法是调用了Arrays.sort()方法,Arrays.sort方法中是调用的TimSort.sort();
然后查看官方文档发现这样一段描述:
The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y,x)) for all x and y. (This implies that compare(x,y) must throw an exception if and only if compare(y, x) throwsan exception.) The implementor must also ensure that therelation is transitive: ((compare(x,y)>0) && (compare(y, z)>0)) implies compare(x, z)>0. Finally, the implementor must ensure that compare(x, y)==0 impliesthat sgn(compare(x, z))==sgn(compare(y, z)) for all z. |
a). sgn(compare(x, y)) == -sgn(compare(y, x))
b). (compare(x, y)>0) && (compare(y,z)>0) 表示 compare(x, z)>0
c). compare(x, y)==0 表示对于任意的z:sgn(compare(x,z))==sgn(compare(y, z)) 均成立
改成:
s1==s2?0:(s1.compareTo(s2)>0?1:-1);
就解决了这个问题。