The moose likes Beginning Java and the fly likes How HashCode value is calculated for objects Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "How HashCode value is calculated for objects" Watch "How HashCode value is calculated for objects" New topic
Author

How HashCode value is calculated for objects

Sudhakar Reddy Kurakula
Ranch Hand

Joined: Aug 19, 2006
Posts: 42
I want to know how the implemention for calculating the hashcodes for objects is provided in Object class.

In the same manner for equals() method also.

I came to know that HashCode() and equals() mehthods have been implemented in string class.

what technique is used in both classes?

can anybody explain me?

Cheers
Sudha
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24057
    
  13

The source code for all the java.* API classes is included in the JDK distribution, in a file named "src.jar" or "src.zip". It's often useful to look at that source to answer questions like these.

For Object, hashCode() is a native method in Sun's JDKs. The value is derived from some native characteristic of the object -- for example, its address in memory. Notice I said "derived from" -- the hashCode is not itself the object's address in RAM, but it may be related to it.

Object.equals() just uses the "==" operator.

String overrides both these methods. String.hashCode() computes a value using all the characters by adding, shifting, multiplying, and operations of this sort. The equation is given on the Javadoc page for the String class. String.equals() compares all the characters of the two strings to see that they're the same.
[ December 31, 2006: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Sudhakar Reddy Kurakula
Ranch Hand

Joined: Aug 19, 2006
Posts: 42
Thanks for giving answer.

Cheers
Sudha
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: How HashCode value is calculated for objects
 
Similar Threads
A question about hashCode
if we override hashCode method is compulsary to override equals method and viseversa.
Reg Hashcodes
Confused in equals working and its overriding
Putting object in HashMap