当重写 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/