G
Gabriel Belingueres
The problem is in
if (!other.getClass().equals(this.getClass())) {
return other.equals(this);
}
this result in an infinite recursive call when you try to compare this
object with some object of a subclass of it.
Oliver asumes that 2 objects are equal if they are both of the same
class, which is not allways correct as you trivially found.
equals(Object) is intentionally informal about the meaning of equality.
The only formal definition is that is must define an equivalence
relation on the comparable objects (reflexive, simmetric and transitive
properties on objects)
Patricia Shanahan ha escrito:
if (!other.getClass().equals(this.getClass())) {
return other.equals(this);
}
this result in an infinite recursive call when you try to compare this
object with some object of a subclass of it.
Oliver asumes that 2 objects are equal if they are both of the same
class, which is not allways correct as you trivially found.
equals(Object) is intentionally informal about the meaning of equality.
The only formal definition is that is must define an equivalence
relation on the comparable objects (reflexive, simmetric and transitive
properties on objects)
Patricia Shanahan ha escrito:
Oliver Wong wrote:
...*: Actually, making equals "aware" of class hierarchies is slightly trickier
than that. I wanted to gloss over this in my above example, but here's a
more complete example implementation:
public class SomeClass {
final int field1;
final String field2;
/*Constructors, getters, and hashcode*/
@Override
public boolean equals(Object other) {
if (other instanceof SomeClass) {
return equals((SomeClass)other);
}
return false;
}
public boolean equals(SomeClass other) {
if (!other.getClass().equals(this.getClass())) {
return other.equals(this);
}
if (this.field1 != other.field1) {
return false;
}
if (!this.field2.equals(other.field2)) {
return false;
}
return true;
}
}
I got worried about whether this code would ever make up its mind, given
a subclass comparison. It doesn't:
public class SomeClass {
final int field1 = 0;
final String field2 = "test";
public static void main(String[] args) {
Object obj1 = new SomeClass();
Object obj2 = new SomeSubClass();
System.out.println(obj1.equals(obj2));
}
/*Constructors, getters, and hashcode*/
@Override
public boolean equals(Object other) {
if (other instanceof SomeClass) {
return equals((SomeClass)other);
}
return false;
}
public boolean equals(SomeClass other) {
if (!other.getClass().equals(this.getClass())) {
return other.equals(this);
}
if (this.field1 != other.field1) {
return false;
}
if (!this.field2.equals(other.field2)) {
return false;
}
return true;
}
private static class SomeSubClass extends SomeClass{
}
}
This program results in a StackOverflowError. obj1 passes the comparison
to obj2, which passes it back to obj1... What am I doing wrong? Are
subclasses of SomeClass required to override equals with specific rules?
Patricia