wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem in hashCode override Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem in hashCode override" Watch "Problem in hashCode override" New topic
Author

Problem in hashCode override

Sidharth Khattri
Ranch Hand

Joined: Sep 16, 2013
Posts: 121

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?


OCPJP 6 - 96%
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4387
    
    8

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

Joined: Sep 16, 2013
Posts: 121

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem in hashCode override