aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Difference between hashCode() and equals() 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 "Difference between hashCode() and equals()" Watch "Difference between hashCode() and equals()" New topic
Author

Difference between hashCode() and equals()

Jambulingam T
Greenhorn

Joined: Jul 24, 2006
Posts: 6
Hi,
Can any one explain me difference between hashCode() and equals() methods.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Have you taken a look at the Java API of the class Object? Each of the methods is explained there. If you not sure of something ask a more specific question.

You can also read this JavaRanch Journal article.
[ July 29, 2006: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
peter cooke
Ranch Hand

Joined: Mar 16, 2004
Posts: 317
I liked the K&B exam prep book explanation.

hashcode - which bucket the thing is in. this implies you understand hashing algorithms.

equals - are two objects equivilant. meaning is my red corvet equivilant to your red corvet. depends on the level of detail we want to get into. When modeling freeway segemants one car is as good as another


overriding these two method are important when dealing with sorted collections such as TreeSet.


CIAO Peter M. Cooke
warren li
Ranch Hand

Joined: May 23, 2006
Posts: 128
They are not the same method.

They are linked when you implement the hashing functions of an object. For details, please refer to the KB book. It is very clear there.


SCBCD 1.3: 94%<br />SCWCD 1.4: 91%<br />SCJP 5: 95%
Anthony Karta
Ranch Hand

Joined: Aug 09, 2004
Posts: 342
I tried the code similar to self-test question. why the size is 2?

as far as I understand if the hashcode is the same for all objects, they will go in the same "Bucket". size should be 1?

Originally posted by peter cooke:

hashcode - which bucket the thing is in. this implies you understand hashing algorithms.




SCJP 5
Ramamoorthy Periasamy
Ranch Hand

Joined: Feb 06, 2006
Posts: 30
The size is 2 because set collection doesnt accept duplicates and so you were overridden the equals method.

1. Find the right bucket using hashCode() method
2. Search the bucket for the right element using equals() method

If the two objects were NOT equal then it is not necessarily their object's hashcode shouldn't be equal, But if they are NOt equal then the performance will be high
Anthony Karta
Ranch Hand

Joined: Aug 09, 2004
Posts: 342
O
1. Find the right bucket using hashCode() method
2. Search the bucket for the right element using equals() method


In K&B, it illustrate if two names (mary and army) have same hashcode, they will go into the same bucket.

In my example, hashcode is always 9, so should they go into just one bucket? or is it because HashSet implementation not allowed duplicate?
Sujittt Tripathyrr
Ranch Hand

Joined: Jun 21, 2006
Posts: 96
Can anybody finally give the difference between these because now i am confusing.

Pls give examples.

Thanks
Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

When we store or search for any element, HashSet/HashMap uses hashCode() and equals() method as produce joint result

We know that storing String, Wrapper like class works fine with HashSet,HashMaps because they String,Wrapper already overridden hashCode() and equals()..... more better way your hashCode() is implemented, faster with be search in HashSet/HashMap.

Now in Anthony;s example, Day class overrides hashCode() which is legal but not efficient, because it provides one bucket for all....but good thing is that equals is better as it compares day....

I am going to discuss the adding procedure by HashSet in your example in detail.
1. JVM executes hashset.add(d1);

This statement first calls hashCode() that returns 9.
As no other element there and d1 is the very first element in HashSet, hence equals method is not called.

So d1 is stored in a bucket with number 9

hashset.size()-----------> 1
2.JVM executes hashset.add(d2)

This statement first calls hashCode() that return 9.
Now hashset find the bucket with 9 for storing d2, but one element does already exist there (d1).
So hashset will decide to compare d2 with d1 by calling d2.equals(d1) which returns false.

Hence both objects are not equals but will be stored in same bucket of number 9
hashset.size()-----------> 2

3.JVM executes hashset.add(d3)

This statement first calls hashCode() that return 9.
Now hashset find the bucket with 9 for storing d3, but two elements already exist there (d1,d2).
So hashset will decide to compare d3 with both d1 and d2.....till get a result true...hopefully...for
d3.equals(d1)...result is true.

Hence both objects(d3,d1) are equals and as per rule, HashSet does not allow duplicate objects...so d3 is not stored.

again hashset.size()-----------> 2


run the code below for getting complete flow.

import java.util.HashSet;

public class TestHashCode {
public static void main(String[] args)
{

Day d1 = new Day("Monday");
Day d2 = new Day("Tuesday");
Day d3 = new Day("Monday");
HashSet hashset = new HashSet();
System.out.println("adding d1....");
hashset.add(d1);
System.out.println("adding d2....");
hashset.add(d2);
System.out.println("adding d3....");
hashset.add(d3);
System.out.println("adding completed....");

System.out.println("size:" + hashset.size());
}
}
class Day {
private String day;
public Day(String day)
{
this.day = day;
}
public boolean equals(Object obj)
{
System.out.println("equals() method "+this.day+".equals("+((Day) obj).day+")");// do not try it at home
if (obj instanceof Day && ((Day) obj).day.equals(this.day)) {
System.out.println("Yes in equals() "+day);
return true;
}
return false;
}
public int hashCode() {
System.out.println("hashCode()");
return 9;
}

}

OUTPUT is
---------------------------------------------------
adding d1....
hashCode()
adding d2....
hashCode()
equals() method Tuesday.equals(Monday)
adding d3....
hashCode()
equals() method Monday.equals(Tuesday)
equals() method Monday.equals(Monday)
Yes in equals() Monday
adding completed....
size:2
------------------------------------------
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Try this one http://www.geocities.com/technofundo/tech/java/equalhash.html
Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

This is a very good link....i appreciated....i have one thing want to discuss with you people.
hashCode() contract from Java 5 API..........says
"If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result."

This means that if both are not equal, then hashCode can be equal/not equal...

but better performance is gained if hashCode is not equals...

Suppose if both objects are not equal by equal()(as d1,d2 are not in above example) method but hashCode is same (9).
Hence during search, first hashset search for hashCode for d1 (suppose we are searching d1)...and in number 9 bucket, two elements are there, then again hashset do second work i.e. to apply equal method by searching object (here d1) with both d1 and d2 (bucket elements). When found, it will return object.

Hence here hashset did overhead by applying equals method.

Other side of story if hashCode return false also, for unequal objects, then d1 and d2 must be in unique individual buckets and hence search only needs hashCode() execution by hashset and no overhead of calling equals() method.

please correct me if i am wrong

Sincerely,
Pawan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Difference between hashCode() and equals()