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.

4
  • 3
    Are you really sure they are different instances? Do a ==. Commented Aug 29, 2013 at 18:51
  • yes, positive, in my logger it records the hashCode right after the object is created and the thread that created it. Threads are different and hash codes are the same. Commented Aug 29, 2013 at 18:51
  • it is possible that two instances can give the same hash code, but this is unlikely. Can you show us some more code? Also you should try setting the field values to something different to double check that they really are different. Commented Aug 29, 2013 at 18:52
  • could you post the Strings that give equal hashcodes? Commented Aug 29, 2013 at 19:07

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

In other words, nobody promised you that hash codes are unique, so you should not write your program in a way that assumes this.
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

1 Comment

Assuming implementer followed, equals() and hashcode() contract.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.