如何在Java中检查两个引用是否都包含同一对象? [英] How do I check in Java whether two references are holding the same object?

查看:67
本文介绍了如何在Java中检查两个引用是否都包含同一对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找C/C ++中相当于Java的指针比较.

假设我正在从第三方调用类的对象的getSomething()方法.我怎么知道getSomething()的实现是每次返回相同实例还是返回对象的不同实例?我不是希望检查两个对象是否相同,但是需要检查它们是否相同.这样做的动机是,如果第三方实现每次都创建一个新实例,则可能可以通过不每次调用该方法来优化代码.假设我在运行时每秒1000次调用getSomething()

从各篇文章中我读到的内容,我不应该依赖hashCode().在这种情况下,该怎么做?

解决方案

根据 == (标识)运算符,引用类型等效时,引用类型指向"同一对象./p>


问题说:

我不是要检查两个对象是否相同,而是需要检查它们是否是相同实例 (重点是我的)

您实际上将平等与身份混合在一起(就像我最初在答案中所做的那样).作为同一实例,是身份.相同的值是平等.

I am looking for a Java equivalent of pointer-comparison in C/C++.

Suppose I am invoking a getSomething() method of an object of a class from a third-party. How do I know if the implementation of the getSomething() is just returning the same instance everytime or returning a different instance of the object? I am not looking to check whether two objects are identical, but need to check if they are the same instance or not. The motivation is, if the 3rd party implementation is creating a new instance everytime, probably I can optimize my code by not invoking the method everytime. Assume getSomething() is invoked by me 1000s of times a second at run-time

From what I read from various articles, I shouldn't rely on hashCode(). In that case what is the way to do this?

解决方案

Reference types are "pointing to" the same object, when they are equivalent according to the == (identity) operator.


The question says:

I am not looking to check whether two objects are identical, but need to check if they are the same instance or not (emphasis mine)

You actually mixed equality with identity (as I did initially in the answer). Being the same instance is identity. Being the same value is equality.

这篇关于如何在Java中检查两个引用是否都包含同一对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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