你如何获得“对象引用”?在重写toString()和hashCode()时java中的对象是什么? [英] How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

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

问题描述

我想在Java中打印对象的对象引用以进行调试。
I.e.根据情况确保对象是相同的(或不同的)。

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.

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

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天全站免登陆