3

I have an class that generates a String object as:

key = "K:" + this.hashCode();

This class doesn't inherit from any other and it does not override hashCode(). I have a situation where I am getting duplicate keys, so two different instances of an object return the exact same hashCode().

How can this happen and what can be done to avoid it? This class is part of an API that I'm using, so I don't have control over it, but if there is some way I can put a wait or something whenever I create an instance of this object, then something like that could work.

Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106

2 Answers2

6

It may happen. You may get same hashcode for two different objects:

As per Object.hashCode() documentation:

It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

what can be done to avoid it? 

Here are few best practices suggested in other SO questions:

Hashcode implementation best practice1

Hashcode implementation best practice2

Still, these are best practices only, not guaranteed to avoid same hashcode. In your case I think you simply shouldn't depend on hashcode.

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167
  • 3
    In other words, nobody promised you that hash codes are unique, so you should not write your program in a way that assumes this. – Jesper Aug 29 '13 at 18:57
0

If the HashCodes are equal it is not a proof that their object are equal!

However if the HashCodes are UNequal the object are UNequal.

Assumed that no random values are chosen during the calculation!

I recommend generating the HashCode from your IDE

Philipp Sander
  • 10,139
  • 6
  • 45
  • 78