Sunday, May 8, 2011

equals and hashCode method key points


equals and hashCode method key points

The Java super class java.lang.Object has two very important methods defined in it. They are -

    * public boolean equals(Object obj)
    * public int hashCode()

public boolean equals(Object obj)
This method checks if some other object passed to it as an argument is equal to the object on which this method is invoked. The default implementation of this method in Object class simply checks if two object references x and y refer to the same object. i.e. It checks if x == y. This particular comparison is also known as "shallow comparison".


public int hashCode()
This method returns the hash code value for the object on which this method is invoked. This method returns the hash code value as an integer and is supported for the benefit of hashing based collection classes such as Hashtable, HashMap, HashSet

if tow object are NOT equls as per equlas(object) method, then they still may have same hashCode, i.e.
unequal objects need not produce distinct hash codes.
Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

When we override equals mthod we have to consider following points
1) Compare objects with (this == obj)
    a)Cheking with "==" will check if both the object has same heap memory reference, then its equals
    b) This will save time as equlas(object) method is cpu expensive

2) Compare the argument with null, if input object is null then return false
    if((obj == null) || (obj.getClass() != this.getClass())) return false; // prefer
    dont use instanceOf operator if(!(obj instanceof Test)) return false; // avoid
    as Test class may have child that will return true here

3) Compare the object with equlas(object) method
4) Implement hashcode method

================================================== 
if I override equlas method and dont implement hashCode then was potential problme will I face
==================================================
Whenever you override the equals method, you must override the hashCode method as well. If you dont do so then it, results in undetermined, undesired behavior of the class when confronted with Java hash based collection classes or any other Java classes. When you insert object to HashMap or HashTable it will give you unpredictable result.

Object which is not implementing hashcode(), and if you use that object as a key, then you have to use same object  which you have use while giving call to put(). Then only you will get expected value for the key, else it will return null. The object which you will use for put() and get() must be same else error prone result.

No comments:

Post a Comment