分析
新增节点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()