本文共 1275 字,大约阅读时间需要 4 分钟。
String 类 的hashCode方法
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
/** * Returns a hash code for this string. The hash code for a * {@code String} object is computed as ** using {@code int} arithmetic, where {@code s[i]} is the * ith character of the string, {@code n} is the length of * the string, and {@code ^} indicates exponentiation. * (The hash value of the empty string is zero.) * * @return a hash code value for this object. */ public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] *
来个例子
/** * Created by tiantao on 2018/6/13. */public class StringTest{ public static void main(String[] args) { //49 System.out.println("1".hashCode()); //49 * 31 + 49 = 1568 System.out.println("11".hashCode()); //49 * 31 * 31 + 49 * 31 + 49 = 48657 System.out.println("111".hashCode()); //49 * 31 * 31 + 50 * 31 + 51 = 48690 System.out.println("123".hashCode()); }}
转载地址:http://bhnmi.baihongyu.com/