单例意味着哈希码总是返回相同的吗? [英] Does singleton means hashcode always return the same?

查看:86
本文介绍了单例意味着哈希码总是返回相同的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象,分别来自同一类的o1和o2.

I have two objects, o1 and o2 from the same class.

如果是o1.hashcode() == o2.hashcode(),我可以说它们是同一个对象吗?

If o1.hashcode() == o2.hashcode(), can I tell they are the same object?

o1==o2旁边,还有其他方法可以告诉单身人士.

Beside o1==o2, is there any other way to tell the singleton.

推荐答案

如果您有该类的单个实例,则==equals比较将始终返回true.

If you have a single instance of the class, the == and the equals comparison will always return true.

但是,hashcode对于不同的对象可以相等,因此不能仅仅通过具有相等的哈希码来保证相等.

However, the hashcode can be equal for different objects, so an equality is not guaranteed just by having equal hashcodes.

此处hashcode合同.

Here is a nice explanation of the hashcode and equals contracts.

检查相等性不足以确保您拥有单身人士,仅确保实例被视为相等.

Checking the equality is not sufficient to be sure that you have a singleton, only that the instances are considered equal.

如果要具有一个Java类的单个实例,则最好使用静态成员和方法.

If you want to have a single instance of a java class, it may be better to make use of static members and methods.

此处 ,展示了几种用于单例的方法.

Here, several approaches to singletons are demonstrated.

正如emory所指出-实际上,您可以覆盖equals以返回随机的内容,从而违反所需的反射性(x.equals(x) == true).由于您无法在Java中覆盖运算符,因此==是确定相同对象的唯一可靠方法.

as emory pointed out - you could in fact override equals to return something random and thus violate the required reflexivity (x.equals(x) == true). As you cannot override operators in java, == is the only reliable way to determine identical objects.

这篇关于单例意味着哈希码总是返回相同的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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