I am using hibernate and need to override equals and hashCode(). I chose to use google-guava’s equals and hashCode helpers.
I wanted to know if I am missing something here.
I have get/set methods for idImage and filePath.
@Entity
@Table(name = "IMAGE")
public class ImageEntity {
private Integer idImage;
private String filePath;
@Override
public int hashCode() {
return Objects.hashCode(getFilePath());
}
@Override
public boolean equals(final Object obj) {
if(obj == this) return true;
if(obj == null) return false;
if(obj instanceof ImageEntity){
final ImageEntity otherImage = (ImageEntity) obj;
return Objects.equal(getFilePath(), otherImage.getFilePath());
}
return false;
}
}
EDIT:
Ran into inheritance and have a sample here
The problem with the
instanceofoperator is that it works taking into account polymorphism, if I may say so.Let’s say, for example, that you do this:
and then you do this:
As the name suggests, that
equalscall will return true, because of theinstanceofoperator.I know this sounds like basic stuff and most people know it, but it’s SOOOO damn easy to forget it. Now, if you want that behaviour, then it’s fine, you implemented
equalscorrectly. But if you consider that anImageEntityobject must not be equal to an (hypothetical)AdvancedImageEntityobject, then either declareImageEntityto befinalOR forget aboutinstanceofand implement yourequalsmethod like this:This will check the object’s true type, no matter what type the reference is. If the
objparameter is an instance of a subclass, it would “slip” byinstanceof. ButgetClassis a lot more strict and won’t allow it.PS: I’m not saying that
instanceofis bad and should not be used. I’m just saying that you must be aware of this particular situation and decide whether to use it taking this into account.