单例意味着哈希码总是返回相同的吗? [英] Does singleton means hashcode always return the same?
问题描述
我有两个对象,分别来自同一类的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屋!