Re: Need clarification on Object.equals.
On Tuesday, December 18, 2012 4:39:27 AM UTC-6, lipska the kat wrote:
On 18/12/12 08:13,
In the following code Node is an abstract class and both Gate and
Monitor are extensions of Node. a and b are distinct objects yet
a.equals(b) is returning true.
public class Foo {
public static void main(String[] argv){
Node a = new Gate();
Monitor b = new Monitor();
System.out.println(a.equals(b)); // --> prints 'true'
}
}
According to the documentation the contract for equals on instances of
class Object is as follows
"The equals method for class Object implements the most discriminating
possible equivalence relation on objects; that is, for any non-null
reference values x and y, this method returns true if and only if x and=
y refer to the same object (x == y has the value true)."
This is obviously the not the case in your example above.
Does the class Node or any of it's superclasses override the equals metho=
d ?
The following code returns false as expected
public abstract class Foo {
public static void main(String args[]){
Foo bar = new Bar();
Baz baz = new Baz();
System.out.println(bar.equals(baz));
}
}
class Bar extends Foo{}
class Baz extends Foo{}
...
However, add the following method to the class Foo
public boolean equals(Object obj){
return true;
}
and re-run the code and we get true.
Has someone been messing with equals ?
lipska
--
Lipska the Kat=EF=BF=BD: Troll hunter, sandbox destroyer
and farscape dreamer of Aeryn Sun
Thanks for your response,
I see where the problem is. I do not directly implement equals, however Nod=
e is an extension of AbstractSet which does redefine equals. As it turns ou=
t I was in the process of rewriting Node so that it no longer extends Abste=
ractSet when the anomaly popped up in test code, so it is actually a mote p=
oint.