你如何获得“对象引用"?当 toString() 和 hashCode() 被覆盖时,java 中的对象? [英] How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

查看:28
本文介绍了你如何获得“对象引用"?当 toString() 和 hashCode() 被覆盖时,java 中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印 Java 中对象的对象引用"以进行调试.IE.以确保对象相同(或不同),视情况而定.

I would like to print the "object reference" of an object in Java for debugging purposes. I.e. to make sure that the object is the same (or different) depending on the situation.

问题是有问题的类继承自另一个类,该类覆盖了通常会给我 id 的 toString() 和 hashCode().

The problem is that the class in question inherits from another class, which has overriden both toString() and hashCode() which would usually give me the id.

示例情况:运行一个多线程应用程序,我(在开发期间)想检查所有线程是否使用资源对象的相同实例.

Example situation: Running a multi-threaded application, where I (during development) want to check if all the threads use the same instance of a resource object or not.

推荐答案

你到底打算用它做什么(你想做的事与你需要调用的内容有所不同).

What exactly are you planning on doing with it (what you want to do makes a difference with what you will need to call).

hashCode,如JavaDocs 中所定义,表示:

hashCode, as defined in the JavaDocs, says:

在合理可行的情况下,类 Object 定义的 hashCode 方法确实为不同的对象返回不同的整数.(这通常通过将对象的内部地址转换为整数来实现,但 Java™ 编程语言不需要这种实现技术.)

As much as is reasonably practical, the hashCode method defined by class 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™ programming language.)

因此,如果您使用 hashCode() 来确定它是否是内存中的唯一对象,这不是一个好方法.

So if you are using hashCode() to find out if it is a unique object in memory that isn't a good way to do it.

System.identityHashCode 执行以下操作:

System.identityHashCode does the following:

为给定对象返回与默认方法 hashCode() 返回的相同的哈希码,无论给定对象的类是否覆盖 hashCode().空引用的哈希码为零.

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.

对于您正在做的事情,听起来像是您想要的……但是您想要做的事情可能并不安全,具体取决于库的实施方式.

Which, for what you are doing, sounds like what you want... but what you want to do might not be safe depending on how the library is implemented.

这篇关于你如何获得“对象引用"?当 toString() 和 hashCode() 被覆盖时,java 中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆