java字符串的hashCode

最近看到一篇关于hashCode的值的问题,提到使用hashCode比较字符串相等的问题。

看了源码,如下:

int h = hash;
        int len = count;
	if (h == 0 && len > 0) {
	    int off = offset;
	    char val[] = value;

            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }

关键的一行:h = 31*h + val[off++];

h初始为0,val[]是char类型的数组,val[off++]拿的是char类型字符的ASCII值

这样一来,不同的字符串,可能会有相同的hashCode值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章