[Logo]
Forums Register Login
Problem in hashCode override
 
This question is from scjptest.com



In the hashCode() override method, return again invokes hashCode() on this.str:
public int hashCode() {
return this.str.hashCode();
}

What does that mean and What will it return?
To see what will it return I added a print statement in hashCode in the above program:

And the output is:
49
49
2

I don't understand how hashCode returns 49 in the output. Can anyone please explain?
(1 like)
It returns the hash code of the str member, which is a String. Have you checked the documentation for java.lang.String#hashCode()? That explains how it's calculated, which explains where the 49 comes from.

As for why it does that: remember that hashCode() needs to be consistent with equals(). The equals() method you've shown uses str to compare HashTest1 objects, so it makes perfect sense that hashCode() is based on str as well - it's the easiest way to make them consistent.
 
Matthew Brown wrote:It returns the hash code of the str member, which is a String. Have you checked the documentation for java.lang.String#hashCode()? That explains how it's calculated, which explains where the 49 comes from.

As for why it does that: remember that hashCode() needs to be consistent with equals(). The equals() method you've shown uses str to compare HashTest1 objects, so it makes perfect sense that hashCode() is based on str as well - it's the easiest way to make them consistent.


Thanks Matthew. I got it
Wink, wink, nudge, nudge, say no more ... https://richsoil.com/cards



All times above are in ranch (not your local) time.
The current ranch time is
Nov 17, 2017 23:58:13.