Comparison method violates its general contract!
程序员文章站
2024-02-22 23:48:34
...
前几天发现通讯录里面的列表不能按照A-Z的顺序排序,当把try catch去掉后,直接闪退。
bug如下:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.TimSort.mergeLo(TimSort.java:743)
at java.util.TimSort.mergeAt(TimSort.java:479)
at java.util.TimSort.mergeCollapse(TimSort.java:406)
at java.util.TimSort.sort(TimSort.java:210)
at java.util.TimSort.sort(TimSort.java:169)
at java.util.Arrays.sort(Arrays.java:2010)
at java.util.Collections.sort(Collections.java:1883)
at project.sirui.newsrapp.information.message.YJLChatSearchActivity$4.onResponse(YJLChatSearchActivity.java:304)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5643)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
一看很蒙逼啊,只知道是Collections.sort()这个方法报的错,就是解决不了,后来把数据弄出来,在观察数据,发现也没有问题,经过百度查看文档,发现这是java7以后对这个方法严格了,Comparator 要满足自反性,传递性,对称性,必须同时满足,否则会报错,网上关于这个的讲解挺多,都没问题,但是必须要结合自己的代码在cv,要不然还是会出现这个问题的,我的错误的代码中没有return 0,多以一直挂。经修改,代码如下:
int lhs_ascii = o1.getFirstPinYin().toUpperCase().charAt(0);
int rhs_ascii = o2.getFirstPinYin().toUpperCase().charAt(0);
if (lhs_ascii == rhs_ascii) {
return 0;
} else if (lhs_ascii < 65 || lhs_ascii > 90) {
return 1;
} else if (rhs_ascii < 65 || rhs_ascii > 90) {
return -1;
}
这样就可以了,但是有些疑惑的是:相同的代码,在别的地方就不会挂,因为我们这个app有俩个通讯录,在通讯录1中就不会挂,唯独通讯录2会发生这种问题,很是感到奇怪!!
上一篇: Visual Studio Code汉化
推荐阅读
-
Comparison method violates its general contract
-
Comparison method violates its general contract!
-
Comparison method violates its general contract!
-
Comparison method violates its general contract!
-
Comparison method violates its general contract
-
java中排序报:Comparison method violates its general contract异常的解决
-
java中排序报:Comparison method violates its general contract异常的解决
-
java 排序报:Comparison method violates its general contract异常的解决方法
-
java 排序报:Comparison method violates its general contract异常的解决方法
-
Comparison method violates its general contract!