Java String hashCode() method returns the hashcode for the String. The hashcode value is used in hashing-based collections like HashMap
, HashTable
etc. The hashCode()
method must be overridden in every class that overrides equals()
method to avoid any unpredicted behavior when used in hash-based collections.
Read More: Contract between hashCode() and equals()
1. String.hashCode() API
The syntax of the hashCode() API is as follows. It does not accept any argument and returns an integer representing the hash code value for this object.
public int hashCode();
The hashcode for a String object is computed as:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
where :
- s[i] – is the ith character of the string
- n – is the length of the string, and
- ^ – indicates exponentiation
The String’s hashCode() overrides the Object.hashCode()
method. This method returns the hashcode as an Integer value.
2. String hashCode() Example
Java program for how to calculate the hashcode of string. In the given example, we are calculating the hashcode of two different strings, and both produce different hashcodes.
System.out.println( "howtodoinjava.com".hashCode() );
System.out.println( "hello world".hashCode() );
Program output.
1894145264
1794106052
Happy Learning !!
Comments