• Post Reply Bookmark Topic Watch Topic
  • New Topic

hashcode  RSS feed

 
Ravi Kumaar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have read that hashCode() function of the object class returns the memory address of that object and it is recommended to implement our own hashCode in our classes for better hashing. Since every object has a unique address, the default implementation seem to provide a good hashing scheme. I am wondering why the default implementation is not the best.
 
Mishra Anshu
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The default implementation of hashCode provided by Object returns something corresponding to the object's address in memory or location in the Java virtual machine's global object array.

But see :-
some of the standard Java classes override this method.

String, for example, overrides the hashCode implementation in Object to return a hash of some or all of the characters making up the String. This allows two String objects with the same characters in the same order to return the same hash value.

So, whenever you want to work on Equals , you need to deal with the hashcode.

Hope it helps !!!
 
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 hashCode() is not the memory address of the object, although it's possible that it's related to it, or to the address of a data structure connected to that object. It's just a number. Note that it's not guaranteed to be unique -- two objects can have the same default hashCode().

That said: go read the Javadoc for java.lang.Object. Both the documentation for hashCode() and equals() talk about the relationship between these two methods: in particular, many parts of the Java APIs assume that if two objects are equal, they have the same hash code. Therefore, if you override equals() for object comparison, you should always override hashCode() as well, or some classes (notably Hashtable and HashMap, and classes that use them) will not work properly with your class.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!