As a Java programmer we know that java.lang.Object is the base class of every class in Java language.
Object class provide some method that provide some default implementation.
Since object class is the base class then method defined by Object class are also available to every class defined in Java, but some time the default implementation of these method is not appropriate for new User Defined classes.
Here we discuses two most important method of object class.
The method Define in object class
public boolean equals(Object obj)
.Indicates whether some other object is "equal to" this one.
The default implementation of equal method compares two objects for equality and returns true if they are equal.
This method only check weather the references of object point to same object or not. means it checks for references not value.
public int hashCode()
.Returns a hash code value for the object.
The value returned by hashCode() is the object's hash code, which is the object's memory address in hexadecimal.
Contract between equal() and hashCode()
1. If two objects are equal, their hash code must also be equal.
2. If you override the equals() method, you must also override the hashCode() method as well.
Some time we do not want to use default implementation of equals() method in our own define class so we must override this method in our class.
Ex. Suppose we have a class Student and we want to compare weather two student are equal or not base on the instance variable studentId.
then we have to override the equal() method to meet our requirement
The equals method implements an equivalence relation. It is:
•Reflexive: For any non-null reference value x , x.equals(x) must return true .
•Symmetric: For any non-null reference values x and y , x.equals(y) must re-
turn true if and only if y.equals(x) returns true .
• Transitive: For any non-null reference values x , y , z , if x.equals(y) returns
true and y.equals(z) returns true , then x.equals(z) must return true .
• Consistent: For any non-null reference values x and y , multiple invocations
of x.equals(y) consistently return true or consistently return false , pro-
vided no information used in equals comparisons on the objects is modified.
• For any non-null reference value x , x.equals(null) must return false .
Here we provide an example how to override equal() and hashCode()
Test the above class