http://www.devx.com/tips/Tip/5839
What is an Object's Hash Code?
Objects in Java have hash codes associated with them. An object's hash code is a signed number that identifies the object (for example, an instance of the parent class). An object's hash code may be obtained by using the object's hashCode() method as follows:
int hashCode = SomeObject.hashCode();
The method hashCode() is defined in the Object class and is inherited by all Java objects. The following code snippet shows how the hash codes of two objects relate to the corresponding equals() method:
1. // Compare objects and then compare their hash codes
2. if (object1.equals(object2)
3. System.out.println("hash code 1 = " + object1.hashCode() +
4. ", hashcode 2 = " + object2.hashCode());
5.
6. // Compare hash codes and then compare objects
7. if (object1.hashCode() == object2.hashCode())
8. {
9. if (object1.equals(object2))
10. System.out.println"object1 equals object2");
11. else
12. System.out.println"object1 does not equal object2");
13. }
By definition if two objects equal (o1.equals(o2)) then calling their hashCode() method must produce the same integer value.
This is essencial to the correct working of a hash table. Don't forget if you override equals, always override hashCode() as well.
No comments:
Post a Comment