Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java's hashCode produce same value for different strings?

Tags:

java

hashcode

Is it possible to have same hashcode for different strings using java's hashcode function?or if it is possible then what is the % of its possibility?

like image 233
Xara Avatar asked Apr 11 '12 08:04

Xara


People also ask

Do same strings have same hashCode?

You can instrument the java. lang. String class so its method hashCode() will always return the same number.

Is hashCode unique for a 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.

Does hashCode return the same value?

The point is that hashcodes can be the same without necessarily guaranteeing that the objects are equal, because the "hashing algorithm" used in the hashCode() method might happen to return the same value for multiple objects.

Can hashCode be same for the different objects?

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.


Video Answer


2 Answers

A Java hash code is 32bits. The number of possible strings it hashes is infinite.

So yes, there will be collisions. The percentage is meaningless - there is an infinite number of items (strings) and a finite number of possible hashes.

like image 130
Mat Avatar answered Sep 23 '22 21:09

Mat


YES. A lot.

Look at following pair

  • "FB" and "Ea"

can return same hash code even though the characters in it are not same.

Basically it is the sum of characters in a string multiplied by an integer.

like image 45
titogeo Avatar answered Sep 23 '22 21:09

titogeo