Hi everyone, I was wondering if anyone can suggest me good online material on Hashcode and Equals method. I studied the material in K&B..its good..As hashcode topic is new to me it will be great if I get more information on this topic. Thanks, vijaya
Thank you very much for your replies. Still I am not clear with the concept of Hashcode. In the example provided by corey I have the following questions(dumb questions !!). 1. When is the Equal method called and to whom does it return the value 2. When is the Hash method called and to whom does it return the value 3. What steps does the h.get(key[i]) follow to get the value for the given key.
I appreciate any help provided to help me understand this concept.
public boolean equals(Object o) { boolean isEqual = false;
if ( o instanceof MyObject ) { if ( ((MyObject)o).a == a ) { isEqual = true; } }
return isEqual; }
public int hashCode() { return a; }
public static void main(String[] args) { Hashtable h = new Hashtable();
MyObject[] keys = { new MyObject(11), new MyObject(12), new MyObject(13), new MyObject(14), new MyObject(15), new MyObject(16), new MyObject(17), new MyObject(18), new MyObject(19), new MyObject(110) };
for ( int i = 0; i < 10; i++ ) { h.put(keys[i], Integer.toString(i+1)); }
long startTime = new Date().getTime();
for ( int i = 0; i < 10; i++ ) { System.out.println(h.get(keys[i])); }
Originally posted by vijaya dev: 1. When is the Equal method called and to whom does it return the value 2. When is the Hash method called and to whom does it return the value 3. What steps does the h.get(key[i]) follow to get the value for the given key.
In each case, you're asking about the inner workings of the hash implementation - in this case, Hashtable, but HashMap is another implementation of the same thing.
The hash implementation is the one that invokes the hashcode() method and the equals() method - it's all done behind the scenes and you need not worry about it. All you need to do is provide valid equals() and hashcode() methods.
What steps the get() method follows are also up to the implementation of the hash table you're using. In general, the get() method will invoke hashcode() on the object you pass to it and it will use the resulting value to index the internal hash table and return to you the object you desire.