2

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
Adam Lee
  • 24,710
  • 51
  • 156
  • 236

4 Answers4

4

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.

Community
  • 1
  • 1
kostja
  • 60,521
  • 48
  • 179
  • 224
  • If you have a single instance of the class the == comparison will always return `true`. If you have a single instance of the class and at least a half-assed implementation, the `equals` comparison will always return true, but the `equals` comparison need not always return true if the implementation is wicked. – emory Oct 20 '12 at 13:56
  • @emory - you're right. `==` is the only reliable source here. Thanks for pointing out, I have edited the answer to reflect this. – kostja Oct 20 '12 at 17:52
3

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

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);
}    
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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.

  1. Within the same program, the result of hashCode() must not change
  2. If equals() returns true when called with two objects, calling hashCode() on each of those objects must return the same result
  3. If equals() returns false when called with two objects, calling hashCode() on each of those objects does not have to return a different result
sy456
  • 1,644
  • 2
  • 14
  • 16