向 hashCode() 添加数字是为了什么?

Adding numbers to hashCode() for what?

我是初学者 我有源码,我找到了这个方法

    @Override
    public int hashCode(){

        return this.name.hashCode() + 57;

    }

它可以从 HashSet 对象中删除重复项,我的问题是为什么 57 存在,我删除了它然后代码运行良好,那么在此方法中使用数字有什么用?

在代码中:

class MyClass {
   public int hashCode(){
      return this.name.hashCode() + 57;
   }
}

这个问题是有效的,因为 this.name.hashCode() 是一个格式良好的 hashCode() 实现(我们可以假设 this.name 是一个 String)。

我认为添加数字是因为方法hashCode()来自Object。假设您有一个 Set,其值类型为 StringMyClass。如果 String 实例与 MyClass.name 实例之一相同,则添加 57 可避免两者共享相同的哈希码。

ya.....使用它是有原因的,因为 Hashcode() 来自对象 class 的 Hashcode() 如果我们使用示例 2 参数存储多个对象但我们想使用等于比较任何一个参数..在这种情况下名称所以添加this.name和57以便生成一个好的哈希码(足够大并且它也将在int范围内..并且没有其他充分的理由)...