简体   繁体   English

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

[英]overriding hashCode, why is this.hashCode() not used?

When overriding the equals() and hashcode() methods in Java why isn't this used often: 覆盖Java中的equals()hashcode()方法时,为什么不经常使用它:

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

Or even the above with a prime introduced: 甚至上面介绍了一个素数:

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

Is this bad practise or does this just simply not work? 这是不好的做法还是只是根本不起作用?

The method: 方法:

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

would lead to an StackOverflowError because it recurse into itself infinitely, unless you replace this with super . 会导致StackOverflowError因为它无限地递归到自身,除非你用super替换this Your second method has the same problem. 你的第二种方法有同样的问题。

In addition, casting a value of type int into an int is useless as well. 另外,将int类型的值转换为int也是无用的。

If you do not provide anything useful new to a method, just don't override it. 如果您没有为方法提供任何有用的新内容,请不要覆盖它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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