相关疑难解决方法(0)

散列函数为什么要使用素数模数?

很久以前,我以1.25美元的价格从交易台上买了一本数据结构书.在其中,哈希函数的解释说,由于"数学的本质",它最终应该由质数修改.

你对1.25美元的书有什么期望?

无论如何,我有多年的时间来思考数学的本质,但仍然无法弄明白.

当存在大量的桶时,数字的分布是否真的更均匀?或者这是一个老程序员的故事,每个人都接受,因为其他接受它?

language-agnostic hash data-structures

323
推荐指数
8
解决办法
9万
查看次数

为什么在hashCode中使用素数?

我只是想知道为什么在类的hashCode()方法中使用素数?例如,当使用Eclipse生成我的hashCode()方法时,总会使用素数31:

public int hashCode() {
     final int prime = 31;
     //...
}
Run Code Online (Sandbox Code Playgroud)

参考文献:

这是关于Hashcode的一篇很好的入门文章和关于我如何找到哈希工作的文章(C#但概念是可转移的): Eric Lippert的GetHashCode指南和规则()

java primes hashcode

160
推荐指数
4
解决办法
6万
查看次数

为具有“可互换”字段的对象实现哈希码

如果“第一个”和“第二个”交换,我希望 Pair 类的两个实例被视为相等,即 Pair(1,2) == Pair(2,1) 应该评估为 true。

    static class Pair {
        int first;
        int second;

        Pair(int first, int second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj == null || obj.getClass() != this.getClass()) {
                return false;
            }

            Pair that = (Pair) obj;
            return (this.first == that.first && this.second == that.second)
                    || (this.second == that.first && this.first == that.second);
        }

        @Override
        public int hashCode() …
Run Code Online (Sandbox Code Playgroud)

java hashcode

5
推荐指数
1
解决办法
100
查看次数

为什么Object.hashcode()在Java中存在冲突?

我在Windows XP上的Hotspot JDK 1.6中运行下面的代码,我运行了两次,我得到了下面的结果.

所以基本上似乎object.hashcode()也有冲突?看起来它没有返回VM中的内存地址.

但是,JDK中的一条评论说价值观应该是截然不同的,任何人都可以解释一下吗?

尽可能合理,Object类定义的hashCode方法确实为不同的对象返回不同的整数.(这通常通过将对象的内部地址转换为整数来实现,但Java TM编程语言不需要此实现技术.)

@return  a hash code value for this object.
@see     java.lang.Object#equals(java.lang.Object)
@see     java.util.Hashtable
Run Code Online (Sandbox Code Playgroud)

这是第一个结果:

i,hashcode(): 361,9578500
i,hashcode(): 1886,9578500
conflict:1886, 361
i,hashcode(): 1905,14850080
i,hashcode(): 2185,14850080
conflict:2185, 1905
9998
Run Code Online (Sandbox Code Playgroud)

这是第二个结果:

i,hashcode(): 361,5462872
i,hashcode(): 1886,29705835
conflict:1887, 362
i,hashcode(): 1905,9949222
i,hashcode(): 2185,2081190
conflict:2186, 1906
9998
10000
Run Code Online (Sandbox Code Playgroud)

我的代码:

@Test
    public void testAddr()
    {
        Set<Integer> s = new TreeSet<Integer>();
        Map<Integer, Integer> m = new TreeMap<Integer, Integer>();
        Set<Object> os = new HashSet<Object>();

        for(int i = 0; i …
Run Code Online (Sandbox Code Playgroud)

java hashcode

2
推荐指数
1
解决办法
1032
查看次数