【Java 里 null 的 hash code 是多少?】
Object o = null;
// Exception in thread "main" java.lang.NullPointerException
// System.out.println(o.hashCode());
点进去看 hashCode() 方法的实现
/**
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
null 也是个对象,是对象就一定有一个 hash code 看 @see 里的 java.lang.System#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.
*
* @param x object for which the hashCode is to be calculated
* @return the hashCode
* @since JDK1.1
*/
public static native int identityHashCode(Object x);
果然 The hash code for the null reference is zero。
再去看 HashMap 里的 put(null, xxx)
呢?
/**
* 果然 key == null 的时候返回的也是 0
*/
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
结论:Java 里 null 的 hash code 是 0。