Java 里 null 的 hash code 是多少? | LIXI.FUN
0%

Java 里 null 的 hash code 是多少?

1
2
3
4
Object o = null;

// Exception in thread "main" java.lang.NullPointerException
// System.out.println(o.hashCode());

点进去看 hashCode() 方法的实现

1
2
3
4
5
6
/**
* @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

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 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) 呢?

1
2
3
4
5
6
7
/**
* 果然 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。

觉得有收获就鼓励下作者吧