As per the below link
Hashcode and equals
So it is assumed that if 2 objects are equal (that is, equals() returns true), then their hashCodes() must retu
It is bad implementation of hashCode()
, You should follow that contract.
equals
has nothing to do with hashcode
independently.
But when you use hashing data structure you should must follow this thing.
First imp thing you should not use random number to implement the hashcode()
method.
@Override
public int hashCode() {
return name.hashcode();
}
@Override
public boolean equals(Object o) {
if(o !=null && o instanceOf Demo)
{
Demo d=(Demo) o;
if(this.d.name==d.name)
{
return true;
}
else
{
false;
}
else
{
return false;
}
}
In Hashcode it is always required that if two objects are equal then their hashCode always have to be the same other wise the hash collections(HashMap, HashSet etc. wont work correctly)
Well in your case one of the implementations of can be -
public int hashCode() {
return this.getName();
}
OR if you want to mix it up a bit -
public int hashCode() {
return String.valueOf(this.getName()).hashCode();
}
You should never implement hashCode
using random numbers! It should always be computed using the same fields as equals
uses. Otherwise, your objects will be unusable as keys in HashMap
, HashSet
, etc.
Some implementations (for instance HashMap
) depend on the fact that when two instances are equal their hashcode should be the same. However, purely using equals will not check hashcodes for those instances.
In the case of a hashmap, elemets are first divided into different hash buckets based on the hashcodes of objects (for performance reasons). Inside a bucket, equals is used to check object equality. If two equal instances don't have the same hashCode
they will end up in different buckets and that might result in unexpected behaviour due to the contract violation.
Actually the idea is that when you implemente the equals
method you should implement the hashCode
method, and if a.equals(b)
then a.hashCode() == b.hashCode()
. Although there isn't anything in the Java compiler or Runtime that enforces this.