• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Working of HashSet  RSS feed

 
Greenhorn
Posts: 3
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have difficulty in understanding the behaviour of Hashset in the following two scenarios.
1.I have overridden the equals method such that it always returns true and kept the default hashCode method.
2.I have overridden the equals method such that it always returns true and also the hashCode method such that it always returns single number.
I have following results respectively
a.Accepts multiple objects of same class type.
b.Accepts single object of same class type even when multiple are inserted.
Also the documentation for Set mentions "sets contain no pair of elements e1 and e2 such that e1.equals(e2)".So here i am unable to understand the behaviour of hashset for case 1 & 2 that is even when equals returns true why does it accept same type of multiple objects.
Following is the code:

Output:
[12, 7, 13, 14, 10, 6, 19, 5, 9, 11, 18, 17, 15, 16, 4, 8, 2]
 
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The hashcode method is not independent of the equals method. Check the Javadoc for hashcode and you will see that objects that are equal according to equals must have the same hashcode. You have broken that contract in your first scenario so the Hashset is getting confused.

Hashset works by creating a series of 'buckets'. It uses the hashcode to decide which bucket an object belongs in, and then it uses equals to see if the new object equals any objects already in that bucket.

In your first scenario your objects all have different hashcodes so they get put into different buckets. The equals method never even gets called.

In your second scenario your objects are all equal according to the equals method and they all have the same hashcode, so the hashset will only store one of them.
 
ShivKumar Suryan
Greenhorn
Posts: 3
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Mike!!!
I now get the concept.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!