本人第一次发帖,写的不好的地方大虾勿喷~
结论:不是,hash code 只是Java 用来标识对象的,你可以形象的把它视为对象的身份证号码。
- 从对象.hashCode() 方法着手
官方API 的说法:
那具体实现是怎么样的?
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <p>
* The general contract of {@code hashCode} is:
* <ul>
* <li>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.
* <li>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.
* <li>It is <em>not</em> 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.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined
* by class {@code Object} does return distinct integers for
* distinct objects. (The hashCode may or may not be implemented
* as some function of an object's memory address at some point
* in time.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
@HotSpotIntrinsicCandidate
public native int hashCode();
结果它是被native 关键字修饰,也就是说具体的实现不是由Java 来实现的,Java 只负责调用!
再有就是注释说:‘As much as is reasonably practical… some function of an object’s memory address at some point in time)’,翻译一下,从最合乎逻辑、切合实际的角度来看,在不同类定义的hashCode() 方法就是应该给不同的对象返回不同的hash code。(Hash code 也许是或者不是通过对象的内存地址来实现。)
其实,有大神自己用Open JDK 去查找hashCode() 的底层实现,可以参照以下文章:
Java Object.hashCode()返回的是对象内存地址?
文章中得出的结论:
Hash code 有5中不同的生成策略:
1) 返回一个Park-Miller伪随机数生成器生成的随机数。
2) 返回将对象的内存地址做移位运算后与一个随机