문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top