• 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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Difference between hashCode() and equals()

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Can any one explain me difference between hashCode() and equals() methods.
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.



 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 342
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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?
 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anybody finally give the difference between these because now i am confusing.

Pls give examples.

Thanks
 
Ranch Hand
Posts: 264
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
------------------------------------------
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try this one http://www.geocities.com/technofundo/tech/java/equalhash.html
 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
It's hard to fight evil. The little things, like a nice sandwich, really helps. Right tiny ad?
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic