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?
Post by:Matthew Brown
, Bartender
(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.
Post by:Sidharth Khattri
, Ranch Hand
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
Post by:autobot
Oh the stink of it! Smell my tiny ad!
Thread Boost - a very different sort of advertising