gpt4 book ai didi

java - Object.toString() 如何获得 "memory address"以及如何模仿它

转载 作者:IT王子 更新时间:2023-10-28 23:33:46 25 4
gpt4 key购买 nike

ObjecttoString 方法的独特之处在于它似乎是Java 中唯一可以查看内存地址的地方。 Object 是如何做到的?

我想知道这样我就可以在我自己的类中模仿它的实现。我不能使用 super.toString() 因为我正在扩展一个已经覆盖 toString 的类。

更新:我的问题的前提是要内存地址,但是答案已经表明这个前提是不正确的,所以我真正要问的是:Object.toString()是怎么做的 返回它的作用,我该如何模仿它?

最佳答案

不是内存地址,是hashCode()。另见 Object.toString()其中说(部分)

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character @, 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:

getClass().getName() + '@' + Integer.toHexString(hashCode())

还有 Object.hashCode()(这通常通过将对象的内部地址转换为整数来实现,但 Java™ 编程语言不需要这种实现技术。) 所以它不是必需的 作为内存地址,如果使用它,它只对 Object 的内部( native )实现可见。

关于java - Object.toString() 如何获得 "memory address"以及如何模仿它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36376339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com