求助Java高手,关于一个程序

来源:百度知道 编辑:UC知道 时间:2024/06/14 00:42:32
public class Alphabet
{
public static void main(String[] args)
{
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println (alphabet);
System.out.println("This string contains " + alphabet.length() + "characters.");
System.out.println("The character at index 4 is " + alphabet.charAt(4) );
System.out.println("The index of the character Z is" + alphabet.indexOf('Z'));
System.out.println("The hash code for this string is " + alphabet.hashCode() );
}
}
程序最后这个Hash code的值最后出来为什么是218640813呢?

去查API就知道了

hashCode
public int hashCode()返回此字符串的哈希码。String 对象的哈希码按下列公式计算:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
使用 int 算法,这里 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。(空字符串的哈希码为 0。)