A boilerplate implementation of an equals(Object otherObj)
reads like this:
@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?
CodePudding user response:
Class<T>
does not override equals
and uses the default Object#equals(Object)
implementation. Therefore, a.getClass().equals(b.getClass())
is equivalent to a.getClass() == b.getClass()
Object#equals(Object)
is implemented as:
public boolean equals(Object obj) {
return (this == obj);
}
CodePudding user response:
a.getClass().equals(b.getClass()) is equivalent to a.getClass() == b.getClass(), it can't instead the above equal method.