我正在使用 hibernate ,需要覆盖 equals 和 hashCode()。我选择使用 google-guava 的 equals 和 hashCode 助手。
我想知道我是否遗漏了什么。
我有 idImage 和 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;
}
}
编辑:
碰到继承有样例here
最佳答案
instanceof
运算符的问题在于它在考虑多态性的情况下工作,如果我可以这样说的话。
例如,假设您这样做:
public class AdvancedImageEntity extends ImageEntity
{
//some code here
}
然后你这样做:
ImageEntity ie = new ImageEntity ();
AdvancedImageEntity advanced_ie = new AdvancedImageEntity ();
boolean this_will_be_true = ie.equals (advanced_ie);
顾名思义,equals
调用将返回 true,因为 instanceof
运算符。
我知道这听起来很基本,而且大多数人都知道,但忘记它实在太容易了。现在,如果您想要这种行为,那很好,您正确地实现了 equals
。但是,如果您认为 ImageEntity
对象不能等于(假设的)AdvancedImageEntity
对象,则可以将 ImageEntity
声明为 final
或忘记 instanceof
并像这样实现您的 equals
方法:
@Override public boolean equals(final Object obj)
{
if(obj == this) return true;
if(obj == null) return false;
if (getClass ().equals (obj.getClass ()))
{
final ImageEntity otherImage = (ImageEntity) obj;
return Object.equals (getFilePath(), otherImage.getFilePath());
}
return false;
}
这将检查对象的真实类型,无论引用是什么类型。如果 obj
参数是一个子类的实例,它会被 instanceof
“滑倒”。但是 getClass
更加严格,不允许这样做。
PS:我并不是说 instanceof
不好,不应该使用。我只是说你必须意识到这种特殊情况,并考虑到这一点来决定是否使用它。
关于java - 我是否使用 Google Guava 正确实现了 equals 和 hashCode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9257211/