Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!