zoukankan      html  css  js  c++  java
  • java1.7之后的比较器特别之处


    在jdk1.7环境下使用Collectons.sort()方法:

      比如:Collections.sort(list, new Comparator<Integer>());

      就可能会出现异常:
         java.lang.IllegalArgumentException: Comparison method violates its general contract!


    意思是:参数不符合要求。
        其实是第二个参数,比较器的问题。

    jdk升级之后,对比较器的逻辑进行了严格要求,所以在大于或者等于或者大于等于的地方,很容易出错。


    解决方案:

     1. 在Collections.sort(xxx,xxx); 方法之前,加上一句话:     System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");  
        使之能够按照升级之前的逻辑来比较。

     2.在比较器中修改,完善逻辑。

       比如:

           public int compare(ComparatorTest o1, ComparatorTest o2) {
             return o1.getValue() > o2.getValue() ? 1 : -1;
          }

          改为:

           public int compare(ComparatorTest o1, ComparatorTest o2) {
             return o1.getValue() == o2.getValue() ? 0 : (o1.getValue() > o2.getValue() ? 1 : -1);
          }

        这样让逻辑更加严谨。


    相关链接:

      http://jxlanxin.iteye.com/blog/1814164

      http://ju.outofmemory.cn/entry/63413

          http://www.ithao123.cn/content-8176238.html


  • 相关阅读:
    java-初始化和清理
    java-字符串
    java-I/O流
    java-反射和代理
    java-执行流程控制语句
    java-访问控制修饰符
    java-异常
    java-注解
    [ Java学习 ] 一道Java好题的详细题解 001
    [ Java学习 ] 查阅资料整理 002
  • 原文地址:https://www.cnblogs.com/neo-java/p/6830205.html
Copyright © 2011-2022 走看看