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;
    }

改成kotlin

fun hasCode2(str: String): Int {
    val toCharArray = str.toCharArray()
    var h = 0
    for (c in toCharArray) {
        h = 31 * h + c.toInt()
    }
    return h
}

测试

arrayOf(
        "ef5346146820565f6dabbca5ef920270",
        "ef5346146820565f6dabbca5ef920271",
        "ef5346146820565f6dabbca5ef920272",
        "ef5346146820565f6dabbca5ef920273",
        "ef5346146820565f6dabbca5ef920274"
).forEach {
    println("${it.hashCode()}  -- ${hasCode2(it)}")
}

结果

-1534838737  -- -1534838737
-1534838736  -- -1534838736
-1534838735  -- -1534838735
-1534838734  -- -1534838734
-1534838733  -- -1534838733

参考

String 的hashCode源码实现原理
为什么在定义hashcode时要使用31这个数呢

你可能感兴趣的:(kotlin基础,hashcode)