java中mergesort函数怎么用,java.util.Arrays.useLegacyMergeSort=true 作用

(原)

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

-Djava.util.Arrays.useLegacyMergeSort=true

04afccf041e81a7eecdfe5ee31c22346.png

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

在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的实现

ab3796deca0e174b9b3accf87622f095.png

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

0fe2c688c5ee2eda7a7bc25411b98ac5.png

旧的排序方式为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算法。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值