Java String hashCode() method returns the hash code for the String. Hash code value is used in hashing based collections like HashMap
, HashTable
etc. This method must be overridden in every class which overrides equals()
method.
1. String hashCode() method
The hash code 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
String hashCode() overrides the Object.hashCode()
. It return the hash code as integer value.
2. Java String hashCode() example
Java program for how to calculate hashcode of string.
public class StringExample { public static void main(String[] args) { String blogName = "howtodoinjava.com"; System.out.println( blogName.hashCode() ); System.out.println( "hello world".hashCode() ); } }
Program output.
1894145264 1794106052
Reference:
^ represents Exclusive XOR operation and not Exponentiation.
Both’re same, Bitwise operators like ^ & >>> >> are heavily used to decide hash across various api implementation classes. These’re tricky to understand, but very interesting if you try to understand why it’s been used.