For Every Equal Object their Hashcode must be equal. Java returns a unique hashcode if we do not override the hashCode() method
/* A program to check hashcode values for object
@Author Myth17
*/
class HashValue
{
int x;
public boolean equals(Object oo)
{
//if(oo instanceof Hashvalue) uncommenting ths gives error.dunno why? :|
HashValue hh = (HashValue)oo;
if(this.x==hh.x)
return true;
else
return false;
}
HashValue()
{
x=11;
}
}
class Hashing
{
public static void main(String args[])
{
HashValue hv=new HashValue();
HashValue hv2=new HashValue();
System.out.println(hv.hashCode());
System.out.println(hv2.hashCode());
if(hv.equals(hv2))
System.out.println("EQUAL");
else
System.out.println("NOT EQUAL");
}
}
Why does uncommenting the line gives compilation error?? If the objects have unequal hashcodes, why are they shown equal even though the default hashcode varies??