Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hashCode uniqueness

Tags:

java

hashcode

Is it possible for two instances of Object to have the same hashCode()?

In theory an object's hashCode is derived from its memory address, so all hashCodes should be unique, but what if objects are moved around during GC?

like image 677
Eleco Avatar asked Sep 04 '09 19:09

Eleco


People also ask

Is a hashCode unique?

Hashcode is a unique code generated by the JVM at time of object creation. It can be used to perform some operation on hashing related algorithms like hashtable, hashmap etc. An object can also be searched with this unique code. Returns: It returns an integer value which represents hashCode value for this Method.

Is hashCode always unique string?

They are not unique. Show activity on this post. By doing it's own hashing of the key String, that code risks the chance that two different key strings will generate the same integer map key and the code will fail in some situations. In general, the code should probably be using Map<String,String> .

Can 2 different objects have same hashCode?

1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.

Can two different strings have same hashCode?

Two same strings/value must have the same hashcode, but the converse is not true. There might be another string which can match the same hash-code, so we can't derive the key using hash-code. The reason for two different string to have the same hash-code is due to the collision.


2 Answers

I think the docs for object's hashCode method state the answer.

"As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)"

like image 105
RichardOD Avatar answered Sep 28 '22 06:09

RichardOD


Is it possible?

Yes.

Does it happen with any reasonable degree of frequency?

No.

like image 44
GWLlosa Avatar answered Sep 28 '22 06:09

GWLlosa