Monday, 5 September 2011

equals() and hashCode() method of Object Class

Object is super class all the classes. So a class can override equals() and hasCode() method of Object class.
When we want to make two different object of a class meaningful equal, we should override equals() method of object in that class.

class Test
{
 int var;
public boolean equals(Object o)
{
if((o instanceOf Test) && ((Test)o.var==this.var))
{
return true;
}else{
return false;
}
}
public int hashCode(){
return x*7;
}
}
here is sample program that shows how to override equals method.

2.hashCode(): It is used by Collection to find the object efficiently. It is used by HashMap, HashTable, etc classes of collection to find the object of a class from Collection efficiently. HashCode should be different for meaningfully different object for efficiency. It is legal to have same hashCode for all object of a class, but it is not efficient while searching using a Collection.

Hope that you might find my article helpfully . For further understanding please read SCJP Book by Kathy Sierra. Will write such good & important topics related to scjp exam daily.


No comments:

Post a Comment