• 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

Confusing behaviour for HashSet

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have written below sample code to understand HashSet uniqueness. I have overridden hashCode() method for one custom class Dog and then tried to create HashSet of "Dog" objects. As per characteristics of HashSet duplicates shouldn’t be allowed that is being checked based on hashCode() value of the object.
In overridden hashCode() method, I have assigned hashCode() to object as one of the string variable hashCode().
The expected result of below program should be 4 Dog objects in HashSet but there are 5 objects and size of HashSet is shown as 5.

Any reason why this behavior? Is there any error in implementation?

 
Manoj Macwan
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got this now. In K&B book they have emphasised on hashCode() method (page 563) for HashSet but missed to specify that object should also override equals() method if you want to explicitly check for duplicates. I need to override equals() method as well in my code and then HashSet will not add new Dog object if dogName is same as previously added object.
 
Bartender
Posts: 2236
63
IntelliJ IDE Firefox Browser Spring Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

The code is ok, but remember that HashMap is not indexed and it does not promise any particular ordering of elements while iterating over it.

Manoj Macwan wrote:I got this now. In K&B book they have emphasised on hashCode() method (page 563) for HashSet but missed to specify that object should also override equals() method if you want to explicitly check for duplicates.


First of all, you should always override equals when you override hashCode and vide versa to keep hashCode/equals contract.
Second, this is mentioned in the book at page 549.
 
sunglasses are a type of coolness prosthetic. Check out the sunglasses on this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic