Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does singleton means hashcode always return the same?

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

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

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

like image 631
Adam Lee Avatar asked Mar 06 '26 06:03

Adam Lee


1 Answers

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

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

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.

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.

EDIT: 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.

like image 75
kostja Avatar answered Mar 08 '26 18:03

kostja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!