Java 对象的内存地址是否就是hash code?

本人第一次发帖,写的不好的地方大虾勿喷~

结论:不是,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) 返回将对象的内存地址做移位运算后与一个随机

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值