[英]Using getClass.equals(otherObj.getClass()) in an implementation of equals(Object otherObj)
A boilerplate implementation of an equals(Object otherObj)
reads like this: equals(Object otherObj)
的样板实现如下所示:
@Override
public boolean equals(Object other)
{
if(this == other)
return true;
if(other == null)
return false;
if(this.getClass() != other.getClass())
return false;
Employee e = (Employee) other;
return (Objects.equals(this.name, e.name) &&
Objects.equals(this.hireDay, e.hireDay) &&
this.salary == e.salary);
}
Can we use:我们可以使用:
if(!this.getClass().equals(other.getClass()))
instead?反而?
Class<T>
does not override equals
and uses the default Object#equals(Object)
implementation. Class<T>
不会覆盖equals
并使用默认的Object#equals(Object)
实现。 Therefore, a.getClass().equals(b.getClass())
is equivalent to a.getClass() == b.getClass()
因此,
a.getClass().equals(b.getClass())
等价于a.getClass() == b.getClass()
Object#equals(Object)
is implemented as : Object#equals(Object)
实现为:
public boolean equals(Object obj) { return (this == obj); }
Since your original condition is this.getClass().= other.getClass()
, you have to write .this.getClass().equals(other.getClass())
, if you were to translate it (but that should be very obvious)由于你的原始条件是
this.getClass().= other.getClass()
,你必须写.this.getClass().equals(other.getClass())
,如果你要翻译它(但那应该是非常明显的)
This line of code这行代码
a.getClass().equals(b.getClass())
is equivalent to相当于
a.getClass() == b.getClass()
it can't instead the above equal method.它不能代替上面的 equal 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.