java.lang.IllegalArgumentException: Comparison method violates its general contract 异常

使用Comparator比较大小时,结果要return 0; return 1; return -1;

分别表示等于、大于、小于

 

   项目中这样操作,导致了异常:java.lang.IllegalArgumentException: Comparison method violates its general contract  

BigDecimal value1 = new BigDecimal(sb1.toString());
BigDecimal value2 = new BigDecimal(sb2.toString());
return value1.subtract(value2).intValue();

修改如下:
if(value1.compareTo(value2) == -1){
return -1;
}

if(value1.compareTo(value2) == 0){
return 0;
}

if(value1.compareTo(value2) == 1){
return 1;
}

具体原因的话是因为1.7的新算法抛的异常,这里有详细解释: http://www.cnblogs.com/JAYIT/p/6170426.html

posted @ 2021-05-21 17:24  mabiao008  阅读(918)  评论(0编辑  收藏  举报