关于java源码HashMap中的Entry属性 final int hash的作用

是不同的key可能拥有同样的hash,所以先要比较hash,再看key是否完全一致。这种情况叫哈希碰撞
■网友
要想理解为什么这样做,还是回归到源码,hashmap 的hash实现在JDK中的实现如下:方法一:static final int hash(Object key) { int h; // h = key.hashCode() 为第一步 取hashCode值 // h ^ (h \u0026gt;\u0026gt;\u0026gt; 16) 为第二步 高位参与运算 return (key == null) ? 0 : (h = key.hashCode()) ^ (h \u0026gt;\u0026gt;\u0026gt; 16);}方法二:static int indexFor(int h, int length) { //jdk1.7的源码,jdk1.8没有这个方法 return h \u0026amp; (length-1); //第三步 取模运算}可以看到在对key取hash的时候先调用了hashCode方法,再来看看这个方法的说明:* \u0026lt;ul\u0026gt; * \u0026lt;li\u0026gt;Whenever it is invoked on the same object more than once during * an execution of a Java application, the {@code hashCode} method * must consistently return the same integer, provided no information * used in {@code equals} comparisons on the object is modified. * This integer need not remain consistent from one execution of an * application to another execution of the same application. * \u0026lt;li\u0026gt;If two objects are equal according to the {@code equals(Object)} * method, then calling the {@code hashCode} method on each of * the two objects must produce the same integer result. * \u0026lt;li\u0026gt;It is \u0026lt;em\u0026gt;not\u0026lt;/em\u0026gt; required that if two objects are unequal * according to the {@link java.lang.Object#equals(java.lang.Object)} * method, then calling the {@code hashCode} method on each of the * two objects must produce distinct integer results. However, the * programmer should be aware that producing distinct integer results * for unequal objects may improve the performance of hash tables. * \u0026lt;/ul\u0026gt; * \u0026lt;p\u0026gt; * As much as is reasonably practical, the hashCode method defined by * class {@code Object} does return distinct integers for distinct * objects. (This is typically implemented by converting the internal * address of the object into an integer, but this implementation * technique is not required by the * Java\u0026amp;trade; programming language.) * * @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();通过说明可以看出,俩个相同的对象,只会生成相同的hash值,然而并没有说明不同的对象一定不会生成相同的hash值,这不是充分不必要条件。所以如楼上所说,是可能存在hash碰撞的。附上一篇分析hashmap的很透彻的文章:Java 8系列之重新认识HashMap
■网友
我觉得楼主的意思是不是对于这个数组来说,同一个下标下存储的所有entry都应该是相同的hash值,为什么还需要再检查一次?我也有点疑问,看看有没有大神解答

■网友
if (e.hash == hash \u0026amp;\u0026amp; ((k = e.key) == key || key.equals(k))) { 这句代码后面是重点,如果是hash值相等了,然后key不相等,但是如果equals相等,虽然不是同一个对象。但是我们依然认为是同一个对象。比如Person p1 = new Person("小明"),Person p2 = new Person("小明");如果在equals方法里面只是判断如果名字相同就是同一个人,就认为是相同。


推荐阅读