In a HashMap collection it is very important for a key object to
implement hashCode() method and equals() method. If hashCode()
method returns same hashcode for all key objects then the hash
collision will be high in HashMap. Also with same hashcode, we
will get same equals method that will make our HashMap
inefficient.
The problem arises when HashMap treats both outputs same instead
of different. It will overwrite the most recent key-value pair with
the previous key-value pair.
So it is important to implement hashCode() and equals() methods
correctly for an efficient HashMap collection.
xxxxxxxxxx
class Test_hash_equal{
public static void main(String[] args){
String a = "Andrew";
String b = "Andrew";
if(a.equals(b)){ //checking the equality of objects using equals() methods
System.out.println("a & b are equal variables, and their respective hashvalues are:" + " "+ a.hashCode() + " & " + b.hashCode());
}
String c = "Maria";
String d= "Julie";
if(!c.equals(d)){ //checking the equality of objects using equals() method
System.out.println("\nc & d are Un-equal variables, and their respective hashvalues are:" + " "+ c.hashCode() + " & " + d.hashCode());
}
}
}