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?

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top