首页 > 其他分享 >Collectons.sort的坑

Collectons.sort的坑

时间:2023-11-08 14:34:50浏览次数:28  
标签:sort Collectons java compare tDepart2 return null

[Request processing failed; nested exception is java.lang.IllegalArgumentException: Comparison method violates its general contract!] with root cause
 java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.util.TimSort.mergeLo(Unknown Source)
    at java.util.TimSort.mergeAt(Unknown Source)
    at java.util.TimSort.mergeCollapse(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at java.util.ArrayList.sort(Unknown Source)
    at java.util.Collections.sort(Unknown Source)

以上是报错。

 

具体代码如下:

 Collections.sort(data, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String o1Bbm1 = CourtUtils.trim(o1.get("CBBM1"));
                String o2Bbm1 = CourtUtils.trim(o2.get("CBBM1"));
                TDepart tDepart1 = CacheUtils.getTDepart(o1Bbm1);
                TDepart tDepart2 = CacheUtils.getTDepart(o2Bbm1);
                if ("".equals(o1Bbm1) || tDepart1 == null) {
                    return 1;
                }
                if ("".equals(o2Bbm1) || tDepart2 == null) {
                    return -1;
                }
                Integer pxh0 = tDepart1.getPxh() == null ? 0 : tDepart1.getPxh();
                Integer pxh1 = tDepart2.getPxh() == null ? 0 : tDepart2.getPxh();
                if (pxh0 == pxh1) {
                    return o1Bbm1.compareTo(o2Bbm1);
                } else {
                    return pxh0 - pxh1;
                }
            }
        });

在对list进行排序时,报错。但是正是环境上是没问题的。所以要排查兼容测试环境的问题,防止正式环境报错。

 

首先要知道,在 JDK7 版本以上,Comparator 要满足自反性,传递性,对称性,不然 Arrays.sort,Collections.sort 会报 IllegalArgumentException 异常。

自反性:当 两个相同的元素相比时,compare必须返回0,也就是compare(o1, o1) = 0;

反对称性:如果compare(o1,o2) = 1,则compare(o2, o1)必须返回符号相反的值也就是 -1;

传递性:如果 a>b, b>c, 则 a必然大于c。也就是compare(a,b)>0, compare(b,c)>0, 则compare(a,c)>0。

最容易出问题的,就是传递性。比如:

假设存在三个元素:stu1, null,stu2,则
compare(stu1, null)= 0,
compare(null, stu2) = 0,
compare(stu1,stu2) =1 很明显违反了传递性原则。

那么,咋改呢?

多进行一次判断,就可以。

Collections.sort(data, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                String o1Bbm1 = CourtUtils.trim(o1.get("CBBM1"));
                String o2Bbm1 = CourtUtils.trim(o2.get("CBBM1"));
                TDepart tDepart1 = CacheUtils.getTDepart(o1Bbm1);
                TDepart tDepart2 = CacheUtils.getTDepart(o2Bbm1);
                if ("".equals(o1Bbm1) || tDepart1 == null) {
                    if ("".equals(o2Bbm1) || tDepart2 == null) {
                        return 0;
                    }
                    return 1;
                }
                if ("".equals(o2Bbm1) || tDepart2 == null) {
                    return -1;
                }
                Integer pxh0 = tDepart1.getPxh() == null ? 0 : tDepart1.getPxh();
                Integer pxh1 = tDepart2.getPxh() == null ? 0 : tDepart2.getPxh();
                if (pxh0 == pxh1) {
                    return o1Bbm1.compareTo(o2Bbm1);
                } else {
                    return pxh0 - pxh1;
                }
            }
        });

 

完活。

 

标签:sort,Collectons,java,compare,tDepart2,return,null
From: https://www.cnblogs.com/notchangeworld/p/17817341.html

相关文章

  • std::sort 传入成员函数指针报错的解决方案
    问题引入有一个类A,A的某个成员函数需要对A的某些变量进行std::sort,同时要调用A的另一个成员函数作为比较器。如代码所示:structA{vector<int>pos={0,4,2,5,3};boolcmp(intx,inty){returnpos[x]<pos[y];}voiddemo(){vector<int>a={2......
  • SortableJS:vuedraggable实现元素拖放排序
    文档:https://sortablejs.github.io/Sortable/github:https://github.com/SortableJS/SortableVue2:https://github.com/SortableJS/Vue.DraggableVue3:https://github.com/SortableJS/vue.draggable.nextnpmhttps://www.npmjs.com/package/vuedraggable#vue2npminst......
  • c: struct sort descending and ascending
     /***@filehello.c*@authoryourname(geovindu)*@brief*@idevscodec11,c17windows10*@version0.1*@date2023-11-05**@copyrightCopyright(c)2023**/#include<stdlib.h>#include<stdint.h>#include<stdio.h......
  • Insertion Sort
    想象一下,冒泡排序交换的两个数一定是原数组的逆序对(反证容易证明:如果不是逆序对,相遇之后不会交换。两个数只有在相遇的时候才会使得下标相对大小互换,相遇之前一定是左的在左,右的在右。而不是逆序对的话,相遇的时候也不会交换,所以就一直不会交换)。因为有序数组一定没有逆序对,所以逆......
  • 『做题记录』[CF1601F]Two Sorts
    [CF1601F]TwoSortslink:https://codeforces.com/problemset/problem/1601/FDescription  有一个数列\(\{a_1,a_2,\ldots,a_n\}\)是一个\(1\simn\)的排列,且所有的数都按照字典序排序,现在给出整数\(n(1\leqn\leq10^{12})\),求\(\left(\sum_{i=1}^n((i-a_i)\bm......
  • 无涯教程-Clojure - sort函数
    返回元素的排序序列。sort-语法以下是语法。(sortseq1)参数   - "seq1"是元素的顺序列表。返回值 - 返回元素的排序序列。sort-示例以下是排序示例。(nsclojure.examples.example(:gen-class));;ThisprogramdisplaysHelloLearnfk(defnEx......
  • AGC304Ex Constrained Topological Sort 题解
    AT一个直接的想法是拓扑排序时从小到大标号:每次在入度为\(0\)的点中找到\(l_{u}\lei\)且\(r_{u}\)最小的\(u\),令\(p_{u}=i\)问题是如果\(r_{u}\)很大,那么\(u\)被标号的优先级很低,会连累\(u\)的后继中\(r\)较小的点做法是倒着拓扑一遍,令\(r_{u}\leftarrow\m......
  • P5156 [USACO18DEC] Sort It Out P 题解
    题意有一个长度为\(n\)的排列\(a_1,a_2,\cdots,a_n\),选出\(\{1,2,\cdots,n\}\)的一个子集,对这个子集中的数依次进行如下操作:设当前数为\(v\),则若\(a_v\)大于\(a_{v+1}\)(如果有的话),就交换。如果小于,则若\(a_v<a_{v-1}\)(如果有的话),就交换。重复上述操作知道\(a_{v-1}<......
  • PAT_A1101 Quick Sort
    Thereisaclassicalprocessnamed partition inthefamousquicksortalgorithm.Inthisprocesswetypicallychooseoneelementasthepivot.Thentheelementslessthanthepivotaremovedtoitsleftandthoselargerthanthepivottoitsright.Given ......
  • javascript: Sorting Algorithms
      /***fileSort.js*ide:vscodeJavaScriptSortingAlgorithms*插件:IntelliSense,JSDoc,CodeLens,DebuggerforChrome,静态代码检查:ESLint,JSHint,FlowLangugaeSupport,StandardJS-JavaScriptStandardStyle,koroFileHeader(文件头注释),测试插件:Mochasideba......