问题
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.
回答1:
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.
回答2:
No, different objects can have the same hashCode()
:
"hypoplankton".hashCode()
"unheavenly" .hashCode()
both return the same 427589249
hash value, while they are clearly not equal.
回答3:
Your question (from the title) seems to be "will hashCode()
always return the same value for the same object"... the answer is no.
The implementation is free to return anything, although to be well behaved it should return the same for the same object. For example, this is a valid, albeit poor, implementation:
@Override
public int hashCode() {
return (int) (Math.random() * Integer.MAX_VALUE);
}
回答4:
The general contract for the hashCode is described below (Effective Java, page. 92). The 3rd item means that the hashCode() results do not need to be unique when called on unequal objects.
- Within the same program, the result of hashCode() must not change
- If equals() returns true when called with two objects, calling hashCode() on each of those objects must return the same result
- If equals() returns false when called with two objects, calling hashCode() on each of those objects does not have to return a different result
来源:https://stackoverflow.com/questions/12987558/does-singleton-means-hashcode-always-return-the-same