Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top