jdk7 中Collections.sort 异常

Collections.sort 异常

java.lang.IllegalArgumentException: Comparison method violates its general contract!
        at java.util.TimSort.mergeHi(TimSort.java:868)
        at java.util.TimSort.mergeAt(TimSort.java:485)
        at java.util.TimSort.mergeForceCollapse(TimSort.java:426)
        at java.util.TimSort.sort(TimSort.java:223)
        at java.util.TimSort.sort(TimSort.java:173)
        at java.util.Arrays.sort(Arrays.java:659)
        at java.util.Collections.sort(Collections.java:217)

代码如下:

Collections.sort(values, new Comparator>() {    
	public int compare(Map.Entry o1, Map.Entry o2) {  
		return (o2.getValue() > o1.getValue() ? 1 : -1);   
	}   
}); 


是对一个Map数组进行排序,更新了jdk版本后报以上异常,查询了先关资料后,修改了代码如下:

Collections.sort(values, new Comparator>() {    
	public int compare(Map.Entry o1, Map.Entry o2) {  
		return o2.getValue().compareTo(o1.getValue());
	}   
}); 

异常解决,参考链接:

http://stackoverflow.com/questions/10234038/compare-method-throw-exception-comparison-method-violates-its-general-contract





你可能感兴趣的:(java语言特性)