简体   繁体   中英

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

When overriding the equals() and hashcode() methods in Java why isn't this used often:

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 . Your second method has the same problem.

In addition, casting a value of type int into an int is useless as well.

If you do not provide anything useful new to a method, just don't override it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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