繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM