wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Difference between hashCode() and equal() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Difference between hashCode() and equal()" Watch "Difference between hashCode() and equal()" New topic
Author

Difference between hashCode() and equal()

Arun Giridharan
Ranch Hand

Joined: Sep 30, 2010
Posts: 290

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.
Chidimma Juliana
Greenhorn

Joined: Jul 14, 2011
Posts: 18
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.
Riza Aktunc
Greenhorn

Joined: Sep 07, 2011
Posts: 24
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.


OCPJP - 93%
Arun Giridharan
Ranch Hand

Joined: Sep 30, 2010
Posts: 290

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
bhanu chowdary
Ranch Hand

Joined: Mar 09, 2010
Posts: 256
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

Joined: Sep 30, 2010
Posts: 290

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 .
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4377
    
    8

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

Joined: Sep 30, 2010
Posts: 290

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

Joined: Apr 06, 2010
Posts: 4377
    
    8

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

Joined: Sep 30, 2010
Posts: 290

does this means we shouldn't override hashCode() method without overriding equal() method ,right ?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4377
    
    8

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.
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
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

Joined: Sep 30, 2010
Posts: 290

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

thank you
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61106
    
  66

http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4377
    
    8

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

Joined: Sep 30, 2010
Posts: 290

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

Joined: Apr 06, 2010
Posts: 4377
    
    8

No. Dennis has shown you the code for equals() in the Object class - you can check it yourself if you don't believe him.
Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 281


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.


http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
Arun Giridharan
Ranch Hand

Joined: Sep 30, 2010
Posts: 290

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

Joined: Mar 12, 2011
Posts: 808
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

Joined: Apr 06, 2010
Posts: 4377
    
    8

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

Joined: Sep 30, 2010
Posts: 290

how does JVM make use of this hashCode() to support the hashing algorithms mentioned earlier ??
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference between hashCode() and equal()