Java String hashCode() 方法

定义和用法

hashCode() 方法返回字符串的哈希码。

String 对象的哈希码计算如下:

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

其中 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。

实例

返回字符串的哈希码:

String myStr = "Hello";
System.out.println(myStr.hashCode());

亲自试一试

语法

public int hashCode()

参数

无参数。

技术细节

返回: int 值,表示字符串的哈希码。