gpt4 book ai didi

java - 重写 hashCode,为什么不使用 this.hashCode() ?

转载 作者:行者123 更新时间:2023-12-02 05:54:36 25 4
gpt4 key购买 nike

当重写 Java 中的 equals()hashcode() 方法时,为什么不经常使用它:

public int hashCode() {
return (int) this.hashCode();
}

或者甚至是上面引入素数的内容:

public int hashCode() {
final int prime = 31; //31 is a common example
return (int) prime * this.hashCode();
}

这是不好的做法还是根本不起作用?

最佳答案

方法:

public int hashCode() {
return (int) this.hashCode();
}

会导致StackOverflowError,因为它会无限递归到自身,除非您将this替换为super。你的第二种方法也有同样的问题。

此外,将 int 类型的值转换为 int 也是没有用的。

如果您没有为方法提供任何有用的新内容,请不要覆盖它。

关于java - 重写 hashCode,为什么不使用 this.hashCode() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23216707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com