[英]Why are this == other and and this.hashcode == other.hashcode() giving different results?
[英]overriding hashCode, why is this.hashCode() not used?
覆盖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
因为它无限地递归到自身,除非你用super
替换this
。 你的第二种方法有同样的问题。
另外,将int
类型的值转换为int
也是无用的。
如果您没有为方法提供任何有用的新内容,请不要覆盖它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.