• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object  RSS feed

 
Mathew Kuruvilla
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could somebody give me an overview of the need to override, the following three methods of the Object class:
hashCode
equals
toString
Thanks.
 
Jeffrey Spaulding
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try Googling "Comparison objects java"
or "do my homework"

 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Javadocs for java.lang.Object contain very detailed descriptions of these methods and how they're used -- worth a read.
 
Srinivasa Raghavan
Ranch Hand
Posts: 1228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mathew,

You need to override equals method to check whether two objects are meaningfully equal. If you dont override equals() method you cant use that in Collections like Hashtable. Now going to hashCode() , you need to override hashCode() if you override equals() method because of the hash code contract.
It says, when x.equals(y) == true then x.hashCode() must be equal to y.hashCode() and if x.equals(y) == false then x.hashCode() should not be equal to y.hashCode().

What will happen, when you use these objects in Hashtable if you dont override hashCode? HashCode will be used While retriving the Objects stored in a Collection, if two Object's are meaningfully equal but has different hashcodes this objects wont be retrived.

As said by Ernest, read java docs so that you can get the concept clearly, further more read K&B book Chapter 7 Pages 1 - 14 it's really great.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!