this is my code .....
- class Object1
-
{
-
private int data;
-
public Object1(int d)
-
{
-
data = d;
-
}
-
public int hashCode()
-
{
-
return 0;
-
}
-
}
-
-
class HashCodeTest
-
{
-
public static void main(String args[])
-
{
-
Object1 o1 = new Object1(100);
-
Object1 o2 = new Object1(200);
-
System.out.println("The hash code for o1: " + o1.hashCode());
-
System.out.println("The hash code for o2: " + o2.hashCode());
-
System.out.println("o1=o2: " + o1.equals(o2));
-
}
-
}
on which basic the EQUALS method is implemented???
as my two objects the hash code is same ....but the EQUALS method returns false.
plz explain.
regards.
You didn't override the equals() method so the Object.equals() method is used
here. Object.equals() uses reference equality, i.e. every two distinct instances
of objects are considered not equal. This implies that only this will result as true:
-
Object o= new Object();
-
System.out.println(o.equals(o));
If objects are considered equal, then the hashCodes should be equal. The other
way around isn't true, e.g. if the hashCodes are equal for two objects then the
objects needn't be equal and if the hashCodes aren't equal then the two objects
certainly aren't equal.
The default implementations of equals() and hashCode() in class Object obey
to this rule. If you overrride them both the new versions should also obey to this
rule.
kind regards,
Jos