名为"equals"的方法应该只用于重载Object.equals(Object),以便预防任何误会。
很有诱惑力的方案是使用特定类型,替换Object作为参数,以保证类型比较检测。
但是,这不会同预想中那样工作。
比如:
class MyClass {
private int foo = 1;
public boolean equals(MyClass o) { // Non-Compliant - "equals" method which does not override Object.equals(Object)
return o != null && o.foo == this.foo;
}
public static void main(String[] args) {
MyClass o1 = new MyClass();
Object o2 = new MyClass();
System.out.println(o1.equals(o2)); // Will display "false" because "o2" is of type "Object" and not "MyClass"
}
}
应该重构为:
class MyClass {
private int foo = 1;
@Override
public boolean equals(Object o) { // Compliant - overrides Object.equals(Object)
if (o == null || !(o instanceof MyClass)) {
return false;
}
MyClass other = (MyClass)o;
return this.foo == other.foo;
}
/* ... */
}