Monday, May 21, 2007

equals and hashcode in Java

equals() and hashCode().
These two are the methods most often overridden after toString() method. All of these methods are defined in java.lang.Object class. These method play an important role when using Collection API of Java. They provide a way to check the equality of records or mappings being put into collection.If you override equals() method, you must override hashCode() to make sure that the objects which are equal return the same hash code.Keep in mind that two equal objects must return the same integer.
In short the requirements of eqauls and hashcode implementation are.
1. equals(null) must return false.
2. If Object1.equals(Object2) returns true, then Object2.equals(Object1) must also return true.
3. If equals() returns true for two objects, both objects must return the same integer from the hashCode() method.
4. If two objects are same they must reproduce same hashcode value for all different invocation of hashcode method unless their state is changed programatically.

Sphere: Related Content

1 comments:

Anonymous said...

What type of information you want to share about hashcode and equal?