This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes HashCodes and Reference Variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashCodes and Reference Variables" Watch "HashCodes and Reference Variables" New topic
Author

HashCodes and Reference Variables

Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 215

Hi all,
I tried to print the value of a reference variable of a class(equals and hashcode not overriden) and i get a value like Classname@hexnumber.
I found out that the hex-number is nothing but the memory address of the object.
BUT,when i override the hashcode and equals,and then i create two equivalent objects,and print the reference variables,I get the same values,because they had same hashCodes,but when i tried to compare them using ==,they were not equal.
So,my question is,even if the reference variables show equal values when printed,why are they not '=='.Do the reference variables store somethong else and display something else?

here is a code





BIG CONFUSION.PLEASE HELP ASAP.

Thanks...
Lanny Gilbert
Ranch Hand

Joined: Jun 11, 2002
Posts: 103
Comparing h and h1 using "==" means that h and h1 are referring to the same exact object in memory, which they aren't
However, h.equals(h1) *should* be true at this point, but h==h1 is not.
Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 215

Hi ,
Yes,I know they don't refer to the same object but why then they give the same value when they are printed?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4343
    
    8

When you print out the values, what's actually happening is that toString() is being used to convert to a String. You haven't overridden toString(), so it's using the version defined in Object.

And if you look up that definition in the Javadocs, you see:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Which means that if you've overridden hashCode() to return the same values, then the output will be the same, even if they aren't the same object.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: HashCodes and Reference Variables
 
Similar Threads
Help needed in understanding the hashCode() method
equals() and hascode() doubt
HashMap Doubt
Equals( ) method semantics
Please Explain (Hashcode)