HashMap源码分析JDK8:tieBreakOrder方法

分析
新增节点key的类在定义时没有实现Comparable接口或者新增节点key实现了Comparable接口但是与当前节点还是compareTo不出结果,那么就动用这个方法来最终决定dir是正是负。

源码分析

	/**
	* 为什么说这个方法能最终决定dir的正、负,
	* 因为它只有-1、1两种输出结果
	*
	* 参数a:新增节点的key
	* 参数b:当前节点的key
    */
   static int tieBreakOrder(Object a, Object b) {
       int d;
       //新增节点的key为空
       //或当前节点的key为空
       //或a和b的类型相同
       if (a == null || b == null ||
           (d = a.getClass().getName().
            compareTo(b.getClass().getName())) == 0)
           d = (System.identityHashCode(a) <= System.identityHashCode(b) ?
                -1 : 1);
       return d;
   }

identityHashCode方法

	/**
     * Returns the same hash code for the given object as
     * would be returned by the default method hashCode(),
     * whether or not the given object's class overrides
     * hashCode().
     * The hash code for the null reference is zero.
     *
     * 无论参数x的类是否重写了hashCode()方法,
     * 都返回Object类中hashCode()方法计算得到的哈希值。
     * x为null的话,返回0
     */
    public static native int identityHashCode(Object x);

identity hash code哪些特点?
(1)一个对象在其生命期中 identity hash code 必定保持不变;
(2)如果a == b,那么他们的System.identityHashCode() 必须相等;
如果他们的System.identityHashCode() 不相等,那他们必定不是同一个对象(逆否命题与原命题真实性总是相同);
(3)如果System.identityHashCode() 相等的话,并不能保证 a == b(毕竟这只是一个散列值,是允许冲突的)。

想深入理解identity hash code可以看看这篇文章:System.identityHashCode(obj) 与 obj.hashcode()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值