• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Difference between hashCode() and equal()

 
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

If two objects have same hashcode value,they are not required to be equal,but if they are equal they must have same hashCode



I'm not understanding the above line.
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What the statement means is that two different objects can have equal hashcodes. However, if the objects are equal, then the hashcodes must also be equal.
 
Greenhorn
Posts: 24
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An annotation might be helpful here:

Assume there are 100 balls whose color can be green, red or blue; and you are required to place balls into 3 boxes according to their colors.

In this example, the green balls have the same hashcode but they may not be equal, since their other features like thickness may vary.

If two balls are equal, all of their features must be equal. This means that their colors must be same, so they must have the same hashcode.


Hope this helps.
 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Arun Giridharan wrote:

If two objects have same hashcode value,they are not required to be equal,but if they are equal they must have same hashCode



I'm not understanding the above line.



when will the hashCode() of 2 objects are equal?? when two reference point to same object ,right ?,else override the hashCode() method ,the equal() method on other hand calls hashCode() method to verify it's equal or not in Object class, since equal () method depends on hashCode() ? right
the bold letters in the quote doesn't make any sense
 
Ranch Hand
Posts: 256
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Suppose if I have a hash algorithm which calculates a hash like this

A B C D E ...... Z
1 2 3 4 5 ...... 26

so for a string "bhanu" my hash will be 2 + 8 + 1 + 14 + 21 = 46
and for the reverse string "unahb" the value is 21 + 14 + 1 + 8 + 2 = 46

In the above case both strings are not the same but the hash value returned is the same. Therefore two objects are not necessarily be equal if the hashcode is same. To determine the equality you have to check for the content of both the strings.
 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

bhanu chowdary wrote:Suppose if I have a hash algorithm which calculates a hash like this

A B C D E ...... Z
1 2 3 4 5 ...... 26

so for a string "bhanu" my hash will be 2 + 8 + 1 + 14 + 21 = 46
and for the reverse string "unahb" the value is 21 + 14 + 1 + 8 + 2 = 46

In the above case both strings are not the same but the hash value returned is the same. Therefore two objects are not necessarily be equal if the hashcode is same. To determine the equality you have to check for the content of both the strings.



but that's theory in practical and gives different hashCode value .
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, because that's not how String's hashCode() method is implemented - the real one is more complicated. But it would have been a perfectly valid hashCode() implementation.

Here's another perfectly allowable hashCode() method. It's not a very good one, but it does not violate the contract and is therefore valid:

 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
but the real equal() method in Object class only calls hashCode() method to verify objects are equal or not, that doesn't prove the contract , right ?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The hashCode() method as implemented by Object does generally return distinct values for distinct objects, though it doesn't have to. The Javadocs say:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)



But that doesn't mean that all implementations have to do that. All that is required is that they follow the contract. Any time you override equals(), you almost certainly have to override hashCode() as well to keep them consistent. And once you do that, the particular implementation in Object is irrelevant. All you can assume is that the contract should be met.
 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
does this means we shouldn't override hashCode() method without overriding equal() method ,right ?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Arun Giridharan wrote:does this means we shouldn't override hashCode() method without overriding equal() method ,right ?


It's more the other way around, although in practice you would override both of them or neither of them. But for the OCPJP exam you need to understand what's allowed, not what's recommended.
 
Ranch Hand
Posts: 808
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all you must have a clear understanding of what these methods are for. Only then will it be at all useful to investigate how they work.

equals
Returns a boolean that indicates whether the given object is equal to this one. This for comparing and evaluating objects.

hashCode
Returns a hash code value for this object. This is NOT for comparing and evaluating objects. It is for locating them in a data structure that uses a hash code to store and retrieve objects.

but the real equal() method in Object class only calls hashCode() method to verify objects are equal or not, that doesn't prove the contract , right ?



NO! equals does NOT call hashCode!

The implementation of equals in the Object class is this:


Only two object references which point to the same memory location are considered equal. On the whole, not very useful, since we would wish the following code to run without error:

So when we design new objects we typically write an equals method that examines the values of that object's attributes.

hashCode has nothing to do with that. It is for efficient storage and retrieval of an object in a hashtable. The hash code points to a bucket where objects can be dumped and then quickly grabbed later. The number of buckets is the number of unique values returned by the class's hashCode method. If hashCode always returns 74, then there will be only one bucket into which all the objects will be dumped. Whenever the data structure has to locate an object it will be pointed to that same bucket. Only after it has found the bucket will it invoke equals in order to find the requested object. It will call equals on every object in the bucket until it finds the one we are looking for.

Now why is it so important that hashCode and equals implementations be coordinated? Because when we insert an element in a data structure that uses hashCode, we need to be sure that it always searches in the appropriate bucket to retrieve that object. Otherwise the object may not be found again!

So objects which do not evaluate to equal may hash to the same location. That just means they were dumped into the same bucket.
BUT objects which DO evaluate to equal MUST hash to the same location.
 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
but still i didn't understand why i need to override hashCode() when i need to override equal() method ? (or viceversa)

thank you
 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Arun Giridharan wrote:but still i didn't understand why i need to override hashCode() when i need to override equal() method ? (or viceversa



The contract, which is what you started the thread by quoting, tells you how your classes should work. Because it's specified in the Object class (look at the descriptions for the equals() and hashCode() methods), then all classes should work like that. And that means that there will be code out there that assumes they work like that.

The collections that use the hashing algorithm that Bear's link describes (like HashSet and HashMap) make use of this contract. There's nothing forcing you do follow it, but if you don't then your classes won't work with these collections. But you'll probably want them to work, and other programmers who have to maintain code you've written will certainly expect them to work.
 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dennis Deems wrote:

NO! equals does NOT call hashCode!

The implementation of equals in the Object class is this:



I am damn sure it must call, hashCode! am i right ? ranchers
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No. Dennis has shown you the code for equals() in the Object class - you can check it yourself if you don't believe him.
 
Ranch Hand
Posts: 300
Eclipse IDE Firefox Browser Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Understanding of hashcode() and equals() tends to more clear when you understand How HashMap works in Java , which is a great example of why you need to correctly override these methods and what could happen in case you don't do that , you could potentially not able to retrieve object from HashMap if hashcode returns two values on different invocation.
 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matthew Brown wrote:No. Dennis has shown you the code for equals() in the Object class - you can check it yourself if you don't believe him.


Isn't that this refer to an address if(this==obj) means it's comparing the address , the address(int value) must be received from hashCode() , internally it must access the hashCode() !!
 
dennis deems
Ranch Hand
Posts: 808
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Arun Giridharan wrote:

Matthew Brown wrote:No. Dennis has shown you the code for equals() in the Object class - you can check it yourself if you don't believe him.


Isn't that this refer to an address if(this==obj) means it's comparing the address , the address(int value) must be received from hashCode() , internally it must access the hashCode() !!



Ah, now I see your confusion. No, the memory address and the hash code are two entirely different things.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Dennis Deems wrote:Ah, now I see your confusion. No, the memory address and the hash code are two entirely different things.


What is true is that the calculation in the hashCode() method in the Object class is based on the memory address. But that's just because it's convenient - the hash code is never used to determine the memory address. All it's there for is to support the hashing algorithms mentioned earlier. And those algorithms require you to override it when overriding equals().
 
Arun Giridharan
Ranch Hand
Posts: 290
Debian Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
how does JVM make use of this hashCode() to support the hashing algorithms mentioned earlier ??
 
Getting married means "We're in love, so let's tell the police!" - and invite this tiny ad to the wedding:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic