首页 > 解决方案 > Netbeans 是否正确创建“等于”方法?

问题描述

从数据库创建实体时,Netbeans 创建equals 方法

    public boolean equals(Object object){
       if(!(object instanceof Department)){
          return false;
       }
       Department other = (Department) object;
       return !(
                 (this.id == null && other.id != null) ||
                 (this.id != null && !this.id.equals(other.id))
               );
    }

并根据以下语句返回语句:

~((A ∧ ~C) ∨ (~A ∧ ~B)) → (~A ∨ C) ∧ (A ∨ B) → (C ∨ B)

等于:

(other.id == null) || (this.id.equals(other.id))

1.这是正确的还是我应该将其更改为:

(this.id != null) && (this.id.equals(other.id))

2.我应该使用像 10 这样的数字,而不是hashCode 方法中的自动递增 id吗?

3.自然 ID 或企业 ID 是否应该完全不可变或可以更改。我的意思是,我应该为它定义一个setter 方法吗?

标签: jpanetbeanshashcode

解决方案


[更新] Netbeans 正确创建了该方法,您可以看到它使用了!在比较中,这就是他在内部使用 OR 和 !equals 的原因:

return !(
         (this.id == null && other.id != null) ||
         (this.id != null && !this.id.equals(other.id))
       );

因此,遵循 Objects.equals 的实现(自 1.7 起),这将是更可取的:

(this.id != null) && (this.id.equals(other.id))

而不是这个equals和hashCode的代码,你可以有:

import java.util.Objects;

@Override
public boolean equals(Object object) {
    if (this == object) return true;
    if (object == null || getClass() != object.getClass()) return false;
    Department department = (Department) object;
    return Objects.equals(id, department.id);
}

@Override
public int hashCode() {
    return Objects.hash(id);
}

这是 Objects.hash 最后调用的实现:

public static int hashCode(Object a[]) {
    if (a == null)
        return 0;

    int result = 1;

    for (Object element : a)
        result = 31 * result + (element == null ? 0 : element.hashCode());

    return result;
}
  1. 关于 hashCode 方法,最好使用与 equals 中相同的字段。在这里,尝试使用将实体标识为一个的字段,例如:

    • 字段名称它是唯一的,然后使用该名称。
    • 字段名称编号是唯一的,然后同时使用。
  2. 创建对象后,您的 Id 字段不应该有设置器。您可以有一个构造函数来接收它,而不是在单元测试中使用,而不是在 setter 中使用。不可变对象是一个很好的方法,但如果你不能,至少标识实例的字段不应该改变。

希望我能帮上忙。


推荐阅读