【发布时间】:2014-02-19 22:15:10
【问题描述】:
我见过许多 java equals() 方法的实现,它们遵循以下几行:
public boolean equals(Object other){
if (this == other)
return true;
//this if code
if (!(other intanceof MyClass))
return false;
//ends here
otherMyClass = (MyClass)other;
//check all the attribute of this and otherMyClass and return true or false
//accordingly
}
如果代码存在问题,是否会为 o1.equals(o2) 返回 true(带有 MyClass 的 o1 对象和 MyClasss 的子类的 o2 对象)?在大多数情况下,这不是预期的行为。
other.getClass() != this.getClass() 不是比上面的粗体更好的比较吗?
【问题讨论】: