zoukankan      html  css  js  c++  java
  • tctip demo页面>

    (原)

    今天看了一下现场的环境,发现有个其它部门的项目用到了这样一个参数:

    -Djava.util.Arrays.useLegacyMergeSort=true
    

      

    于是查看了一下什么作用。

    在JDK1.6和JDK1.7的版本中,使用comparator排序可能在1.6版本中正常运行,而在1.7版本有时会报异常,IllegalArgumentException(异常的内容大概是:Comparison method violates its general contract!)。

    在JDK7的不兼容列表中,可以看到这样一条消息:

    Area: API: Utilities  
    Synopsis: Updated sort behavior for Arrays and Collections may throw an IllegalArgumentException  
    Description: The sorting algorithm used by java.util.Arrays.sort and (indirectly) by java.util.Collections.sort has been replaced.   
    The new sort implementation may throw an IllegalArgumentException if it detects a Comparable that violates the Comparable contract.   
    The previous implementation silently ignored such a situation.  
    If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort,   
    to restore previous mergesort behavior.  
    Nature of Incompatibility: behavioral  
    RFE: 6804124 
    

    大概意思就是 Arrays.sort方法和Collections.sort(底层也是Arrays.sort)方法被替换了,如果违反了新的排序规则就可能会出现IllegalArgumentException异常(这里是可能,不是一定)。之前的方法会忽略掉一种情况,如果想使用之前的方法,这里提供了一个新的参数,java.util.Arrays.useLegacyMergeSort去还原之前的方法。

    再来看看Arrays.sort的实现

    它是有二种排序方法,legacyMergeSort和TimSort。

    旧的排序方式为legacyMergeSort,新的为TimSort,如果要用旧的排序方式,可以在系统属性中加上 java.util.Arrays.useLegacyMergeSort=true 这个参数。

    再看看Collections.sort方法的说明

    大概意思新的TimSort排序方法的实现需要满足三种情况:

    • sgn(compare(x, y)) == -sgn(compare(y, x))
    • ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0
    • compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z

    对于函数sgn(compare(x,y)),由于compare(x,y)的返回结果有0、1、-1三种,sgn(x)的结果也有三种,

    1、当compare(x,y) < 0 时,sgn(compare(x,y))结果为-1

    2、当compare(x,y) = 0 时,sgn(compare(x,y))结果为0

    3、当compare(x,y) > 0 时,sgn(compare(x,y))结果为1

    最容易出错的情况就是自己写的比较器只写了1和-1的情况,而没有写0,如:

    return x > y ? 1 : -1; 
    

    这样会导至当x == y时,compare(x,y)的结果为 -1,此时sgn(compare(x,y)) = -1,这与第一种满足条件sgn(compare(x, y)) == -sgn(compare(y, x))相违背。所以会抛出IllegalArgumentException异常。

    对于 x > y ? 1 : -1 ,当x == y时,也只是可可能会抛出异常,什么会抛出该异常,这要取绝于TimSort算法。

  • 相关阅读:
    cookie,session,token
    自己动手写一个简易对象关系映射,ORM(单例版和数据库池版)
    Python,针对指定文件类型,过滤空行和注释,统计行数
    MySQL 数据类型
    MySQL 基础小技巧
    Python测量时间,用time.time还是time.clock
    [计算机网络]想出网关?你需要懂得这些
    [数据结构与算法]05 Stack 经典面试题之判断字符串是否合法( Java 版)
    [自考总结]想要去的远方,终有一天会到达
    [数据结构与算法]04 Link List (链表)及单链表反转实现
  • 原文地址:https://www.cnblogs.com/LeeScofiled/p/8652310.html
Copyright © 2011-2022 走看看