先来看一个例子

  

public static void main(String[] args) {

String s ="Ea"; 

String d ="FB"; 

System.out.println(s.hashCode());

System.out.println(d.hashCode());

}

结果出乎你的意料,因为打印出来的值是一样的。


查看了java String 类的hashCode 重写方法,发现它是以字符的值作为对象来计算的。

  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;

    }

这样看来,是以字符 char 类型来转化Int 计算的。

又翻了些资料,对于char 的计算转化是以 ascii 码来计算的。

那么对于上面的例子,我们可以还原一下:

public static void main(String[] args) {

String s ="Ea"; 

String d ="FB"; 

System.out.println(s.hashCode());

System.out.println(d.hashCode());

char value[] = "Ea".toCharArray();

char value2[] = "FB".toCharArray();

System.out.println((int)value[0]+" "+(int)value[1]);

System.out.println((int)value2[0]+" "+(int)value2[1]);

System.out.println(31*69+97);

System.out.println(31*70+66);

}

运算结果如下 :

2236

2236

69 97

70 66

2236

2236



由于计算结果的一样,所以这两个字符串的hashCode也是一样的。

所以,以后对于hashCode要慎用了。