String的hashCode

落日映苍穹つ 2024-04-20 00:49 117阅读 0赞

hashCode方法源码:

  1. /**
  2. * Returns a hash code for this string. The hash code for a
  3. * {@code String} object is computed as
  4. * <blockquote><pre>
  5. * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
  6. * </pre></blockquote>
  7. * using {@code int} arithmetic, where {@code s[i]} is the
  8. * <i>i</i>th character of the string, {@code n} is the length of
  9. * the string, and {@code ^} indicates exponentiation.
  10. * (The hash value of the empty string is zero.)
  11. *
  12. * @return a hash code value for this object.
  13. */
  14. public int hashCode() {
  15. int h = hash;
  16. if (h == 0 && value.length > 0) {
  17. char val[] = value;
  18. for (int i = 0; i < value.length; i++) {
  19. h = 31 * h + val[i];
  20. }
  21. hash = h;
  22. }
  23. return h;
  24. }

根据String中的代码,可以知道value存储该字符串的各个字符。
例如String str = “123”,
‘1’ 49
‘2’ 50
‘3’ 51
则value值为49,50,51

  1. /** The value is used for character storage. */
  2. private final char value[];
  3. /** Cache the hash code for the string */
  4. private int hash; // Default to 0
选择31的原因

选择31是因为31是一个质数。当一个数乘以2时,直接拿该数左移一位,最后一位补0.
在存储数据计算hash地址的时候,我们希望尽量减少有同样的hash地址。
所以选择系数的时候,要选择尽量长的系数,并且让乘法尽量不要溢出。
31的乘法可以有i*31==(i<<5)-1来表示。并且31只占用5bits

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读