Java字符串哈希码 String hashCode() 示例代码

Java String hashCode()方法返回字符串的哈希码。哈希码值是判断两个对象是否相等的必要条件之一,在HashMap,HashTable等中具有十分重要的作用。

字符串 hashCode() 方法

String 的源代码中,hashCode() 方法的代码如下:

private final char value[];
private int hash; // Default to 0
public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}
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]

其中:

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

关于hashCode()计算过程中,为什么使用了数字31,主要有以下原因:

1、使用质数计算哈希码,由于质数的特性,它与其他数字相乘之后,计算结果唯一的概率更大,哈希冲突的概率更小。

2、使用的质数越大,哈希冲突的概率越小,但是计算的速度也越慢;31是哈希冲突和性能的折中,实际上是实验观测的结果。

3、JVM会自动对31进行优化:31 * i (i << 5) – i

Java String hashCode() 示例

通过 hashCode() 方法计算字符串的哈希值。

public class StringHashCode {

    public static void main(String[] args) {
        String mapull = "mapull.com";
        System.out.println(mapull.hashCode());
        System.out.println("码谱".hashCode());
        System.out.println("hello world".hashCode());
    }
}
-1891391508
988240
1794106052

hashCode() 与 equals() 方法

要判断两个对象是否相等,我们往往会使用到 equals() 方法。要想 equals() 相等,必须要 hashCode()相等

标签: