集合排序问题

        在之前项目中有根据学年的list进行排序的需求,之前在本地运行没有问题,在集成之后,数据库数据改变了之后报错:

Exception in thread"main" java.lang.IllegalArgumentException: Comparison

method violates itsgeneral contract!

比较方法违反了契约。

        代码中是用的Collections.sort()方法:

public void listSortGrade(List> institutionList) throws Exception {
		// resultList是需要排序的list,其内放的是Map
		// 返回的结果集
		Collections.sort(institutionList, new Comparator>() {
			public int compare(Map o1, Map 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();

集合排序问题_第1张图片

然后查看官方文档发现这样一段描述:

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.

就是说传入的compare得满足一下规则:

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 表示对于任意的zsgn(compare(x,z))==sgn(compare(y, z)) 均成立


那么上面的代码在s1=s2的时候,不满足a条件,因为s1.compareTo(s2)>0?1:-1这个判断当s1=s2的时候,都返回-1,那么就不满足a条件了。所以会报错。

改成:

s1==s2?0:(s1.compareTo(s2)>0?1:-1);
就解决了这个问题。



你可能感兴趣的:(集合排序问题)