Object.toString() 返回的到底是不是内存地址

本文详细解释了Java中toString()方法的功能及其实现原理,并澄清了toString()不是返回对象的内存地址这一常见误解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

从 java.lang.Object 原码中可以看到 toString() 方法,此方法是一个公有方法,所有的类都会继承此方法,也可以复写此方法。

    /**
     * Returns a string representation of the object. In general, the
     * {@code toString} method returns a string that
     * "textually represents" this object. The result should
     * be a concise but informative representation that is easy for a
     * person to read.
     * 返回的对象的字符串表示形式,通常情况下,toString() 方法返回一个字符串,该结果应该简洁但信息
     * 丰富,让人易于阅读。建议所有子类重写此方法。
     * It is recommended that all subclasses override this method.
     * <p>
     * The {@code toString} method for class {@code Object}
     * returns a string consisting of the name of the class of which the
     * object is an instance, the at-sign character `{@code @}', and
     * the unsigned hexadecimal representation of the hash code of the
     * object. In other words, this method returns a string equal to the
     * value of:
     * 换句话说,这个方法返回的字符串等价于 类名+@+对象的哈希码的十六进制表示
     * <blockquote>
     * <pre>
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * </pre></blockquote>
     *
     * @return  a string representation of the object.
     */
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

所以,通过查看Java API 文档,toString() 并不是 对象的内存地址,

经常有人会通过 System.out.println(yourObj) 打印出来的字符串说成是对象的内存地址,println() 内部依然是调用了 yourObj.toString() 方法,以后再有人说toString() 打印的是对象的内存地址的时候,可以直接反驳他。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值