Win a copy of Classic Computer Science Problems in Swift this week in the iOS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem in hashCode override  RSS feed

 
Ranch Hand
Posts: 125
Java Linux Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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?
 
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sidharth Khattri
Ranch Hand
Posts: 125
Java Linux Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!