-
hashCode
public int hashCode()
Returns a hash code for this string. The hash code for aStringobject is computed ass[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using
intarithmetic, wheres[i]is the ith character of the string,nis the length of the string, and^indicates exponentiation. (The hash value of the empty string is zero.)
Ideally, the hash function will assign each key to a unique bucket, but this situation is rarely achievable in practice (usually some keys will hash to the same bucket.
hashCode() vs equals() Method
- If object1 and object2 are equal according to their
equals()method, they must also have the same hash code. - If object1 and object2 have the same hash code, they do NOT have to be equal too.