相关疑难解决方法(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'add'方法调用何时等于?

我在HashSet比较中做了这个测试而equals 没有被调用

当farAway = false时,我想考虑等于(检查两个点距离的函数)

完全可编译的代码,你可以测试它,并告诉为什么在这个例子中没有调用equals.

public class TestClass{
     static class Posicion
    {
        private int x;
        private int y;

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Posicion other = (Posicion) obj;
            if ( farAway(this.x, other.x, this.y, other.y,5)){   
                return false;
            } 
            return true;
        }

        @Override
        public int hashCode() {
            int hash = 7; hash = 59 * hash + this.x; hash = 59 * …
Run Code Online (Sandbox Code Playgroud)

java comparison equals hashset

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

标签 统计

java ×2

algorithm ×1

comparison ×1

equals ×1

hash ×1

hashset ×1

string ×1