Java hashCode() Method

Java String类Java String Class


The hashCode() method is used to return the hash code of a string.

The hash code of a string object is calculated according to the following formula:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

Using int arithmetic, where s[i] is the ASCII code of the i-th character of the string, n is the length of the string, and ^ denotes exponentiation. The hash value of an empty string is 0.

Syntax

public int hashCode()

Parameters

  • None.

Return Value

Returns the hash code value of the object.

Example

Example

public class Test {
        public static void main(String args[]) {
                String Str = new String("www.example.com");
                System.out.println("The hash code of the string is:" + Str.hashCode() );
        }
}

The output from the above program is:

字符串的哈希码为 :321005537

Java String类Java String Class

Other Extensions