相关疑难解决方法(0)

为什么String中的Java hashCode()使用31作为乘数?

每Java文档中,哈希代码String对象被计算为:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
Run Code Online (Sandbox Code Playgroud)

使用int算术,其中s[i]是 字符串的第i个字符,是字符串n的长度,并^指示取幂.

为什么31用作乘数?

我知道乘数应该是一个相对较大的素数.那么为什么不是29岁,37岁,甚至97岁?

java string algorithm hash

461
推荐指数
11
解决办法
14万
查看次数

HashSet与List性能

很明显,泛型HashSet<T>类的搜索性能高于泛型List<T>类.只需将基于散列的密钥与线性方法进行比较即可List<T>.

但是,计算散列键本身可能需要一些CPU周期,因此对于少量项目,线性搜索可以是一个真正的替代HashSet<T>.

我的问题:收支平衡在哪里?

为了简化场景(并且公平),我们假设List<T>该类使用元素的Equals()方法来标识项目.

.net collections hash performance list

374
推荐指数
8
解决办法
18万
查看次数

获取适当的哈希索引C++

我已经尝试了一切.即使是java的论坛:

java.lang.String.hashCode():

s[0]*(31^(n-1)) + s[1]*(31^(n-2)) + ... + s[n-1]
Run Code Online (Sandbox Code Playgroud)

我把它解释为一个总和:虽然我不太清楚如何处理s [n-1];

int hashmap::hashstr( const char*const str )
{
    int result = 0;
    int i = 0;
    int j = 0;
    int k = 0;
    unsigned n = 0;
    for ( ; str[n] != NULL; ++n ); // how many characters?

    while ( j != n ) // no more characters
    {
        result += str[i] * ( 31 ^ ( n - k ) );
        j++;
        i++;
        k++;
    }
    return result …
Run Code Online (Sandbox Code Playgroud)

c++

0
推荐指数
1
解决办法
430
查看次数

标签 统计

hash ×2

.net ×1

algorithm ×1

c++ ×1

collections ×1

java ×1

list ×1

performance ×1

string ×1