hashcode() and equals() methods of Java

Filed Under (JAVA) by Chetan Pagar on 13-12-2011

Yes.. its me too who always get confused while telling answer of question the use of hashcode() and equals method in java. Finally I came on following best answer which explain use and implementation of hashcode() and equals method in java.

 

hashcode() :- An important method within Java. It’s part of Object class, means it’s by default available within the class you are creating. Remember one thing that hashcode is nothing but an id (integer number) assigned to an object by Java Virtual Machine(JVM), it’s the one who get used to compare two object of a class with equal method. Created java object will get referenced by this haschcode only. Hash Code is actually a method which is overriden always when the equals() method is overridden.

class Chetan
{

}  now if we try to create two objects from this java class as

Chetan obj=new Chetan();
Chetan obj1=new Chetan();

here the comparison (obj==obj1) condition is false because, both the obj and obj1 return the different hashcode unique id number.

 

equals() :-  It checks the equivalence of not null java objects. While using this it is generally necessary to override the hashCode method whenever this method is overridden. Means for both equal objects must have equal hash codes.

Share