Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet Problem

 
garima jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I wrote the above program. Output is true and false. Why for line# 1 output is true. Since Dog class does not implement hashCode and Equals method, Object's class hashCode will be used which returns different no for any input value. So, search in bucket different from where the elementwas stored should lead to element not found. Please tell where I am wrong. Thanks, Garima
 
Henry Wong
author
Marshal
Pie
Posts: 20989
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why for line# 1 output is true. Since Dog class does not implement hashCode and Equals method, Object's class hashCode will be used which returns different no for any input value.


The Object's hashCode() and equals() method is designed to hash on the identity of the object -- meaning you can find the object, if it is the same instance.

And noticed that you used the object referred to by the d1 variable, for both add() and contains(). It is the same object. Hence, true.

Henry
 
garima jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry, I got it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic