• 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算法。

  • 相关阅读:
    自制编译器 青木峰郎 笔记 Ch5 基于JavaCC的解析器描述
    自制编译器 青木峰郎 笔记 Ch4 基于JavaCC的扫描器的描述
    自制编译器 青木峰郎 笔记 Ch3 词法分析的概要
    自制编译器 青木峰郎 笔记 Ch2 Cb和Cbc
    自制编译器 青木峰郎 笔记 Ch1 开始制作编译器
    POJ 1201 Intervals 差分约束,最短路,RE会报TLE 难度:1 差分约束背景知识需联想证明
    POJ 3276 The Cow Lexicon DP 难度: 0
    POJ 1276 Cash Machine DP 难度: 0
    Java大数练习
    HDU 4344-Mark the Rope-大数素因子分解
  • 原文地址:https://www.cnblogs.com/LeeScofiled/p/8652310.html
Copyright © 2020-2023  润新知