Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashcode().............

 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


here two different objects are created.
they are meaningfully equal so output is true.
if two objects are equal the hashcode should be same....?

contract is only for collections or anywhere?

how hashcode should be same?
[ November 12, 2008: Message edited by: Ganeshkumar cheekati ]
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes if the two objects are equal according to equals() then the hashcode must also be equal.
these methods are Object's methods, not Collections.

Preparing Scjp 1.5
 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes those two methods belongs to Object class.

if we override equals() then we should override hashcode().

if we cant override then it wil giv unreliable results.

i havent override equals() in my code but output is true.....

why?
[ November 12, 2008: Message edited by: Ganeshkumar cheekati ]
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
post your code.
 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

this is my code....
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you must override them in order to deal with collections to check the objects are equal or not and hashcode too. Because some collections are storing datas according to the hash code value(Hashing algorithms). for eg. hashtable,HashMap,HashSet.

i hope this clears you.

Preparing Scjp1.5
 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok i got it...

the String class and the wrapper classes have overridden
the equals() method (inherited from class Object), so that you could compare
two different objects (of the same type) to see if their contents are meaningfully
equivalent.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic