2

我正在处理现有项目。我有以下用户类的 equals 方法。当我将相等与 equals 进行比较时,我得到了错误

if (getClass() != other.getClass()) {
  return false;
}

完整equals代码:

@Override
public boolean equals(Object obj) {
  if (this == obj) {
    return true;
  }

  if (obj == null) {
    return false;
  }

  User other = (User) obj;
  if (getClass() != other.getClass()) {
    return false;
  }

  if (this.getUserId() == null) {
    if (other.getUserId() != null) {
      return false;
    }
  } else if (!this.getUserId().equals(other.getUserId())) {
    return false;
  }

  return true;
}

我需要在这里检查班级类型吗?如果是,为什么我的用户类别不同?为什么我不能像下面那样检查类类型?

if (!(obj instanceof User)){
  return false;
}
4

7 回答 7

3
if (getClass() != other.getClass()) {
        return false;
    }

此项检查应在铸造之前进行:

User other = (User) obj;

instanceof和之间的区别在于getClass()后者确保类型不是子类型。所以:

User user = new SubUser();
boolean a = user instanceof User;
boolean b = user.getClass() == User.class;
System.out.println(a);
System.out.println(b);

会打印:

true
false
于 2013-10-30T09:06:43.443 回答
0

对于你的问题,你应该把

 getClass() != other.getClass()

 User other = (User) obj;

平等是一个有趣的问题。并且很多人都讨论过。在Programming in Scala 2nd Chapter30中可以看到关于相等性的详细讨论。

于 2013-10-30T09:15:00.050 回答
0

正如我发现的,来自休眠层/DAO 的用户类不是直接的用户类。它是用户或代理的子类。所以,当我检查 obj.getClass() 时,它给出了错误。

在这种情况下,最好不要与 getClass() 进行比较。

我检查了instanceof。

于 2013-11-15T06:23:21.213 回答
0

您应该使用该instanceOf方法来避免ClassCastException以后。如果您使用错误的对象类型的 equals 方法,将抛出此异常。

于 2013-10-30T09:03:36.150 回答
0

Joshua Bloch的Effective Java一书提供了非常好的建议来实现许多人们可能会考虑的标准情况。它包括一种实现该方法的equals方法。

这是一个修改后的实现:

@Override
public boolean equals(Object obj) {
  if (this == obj) {
    return true;
  }

  if (!(obj instanceof User)) { // this covers the null check
    return false;
  }

  User other = (User) obj; // this is now safe

  if ((this.getUserId() == null) && other.getUserId() != null) {
      return false
  } else if ((this.getUserId() != null) && !this.getUserId().equals(other.getUserId())) {
    return false;
  }

  return true;
}

这不是很明显,但是instanceof检查返回falsenull仅仅是因为无法识别它们的类型(即空值是无类型的)。

于 2013-10-30T09:12:35.790 回答
0

首先,我认为你应该反转线条

        User other = (User) obj;
        if (getClass() != other.getClass()) {
            return false;
        }

成为

    if (getClass() != other.getClass()) {
        return false;
    }
    User other = (User) obj;

其次,equals 方法在 java 集合库和许多其他库中都是一个重要的方法,因此您应该真正考虑任何实现细节。

假设您有一个 Employee 类(带有一个 id)被子类化为 Manager,所以您可以考虑在 Employee 上编写一个 equals 方法,只检查 id 就可以了。但是,你呢?这取决于。

因此,如果您签入员工的 equals 方法,如果您通过经理,它将返回 true。但是,如果您使用 getClass 检查类是否相等,当您通过管理器时,它将返回 false。

假设这两个类分别存储在数据库中的员工表和经理表中,数据库将 id 作为列定义为自动增量列。这意味着您可以拥有 id 为 100 的员工与 id 为 100 的经理完全不同的人。

另一方面,您可以拥有一个存储所有员工和经理的员工表。因此,如果您有一个 ID 为 100 的员工对象和一个 ID 为 100 的经理,那么他们必须是同一个人。

于 2013-10-30T09:13:33.357 回答
-1

在这里您声明您没有任何 User 子类,因此您可以使用 instanceof 检查。

于 2013-10-30T09:05:35.990 回答