equals()仅依赖于ID是否合适? [英] Is it proper for equals() to depend only on an ID?

查看:178
本文介绍了equals()仅依赖于ID是否合适?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有课用户

public class User {
  private Long id;
  private String name;
  private Integer age;
  private BigDecimal account;
  // other fields, getters and setters
}

是否合适覆盖等于方法如下?

Is it proper to override the equals method as follows?

@Override
public boolean equals(Object ob) {
   if (ob == null) {
       return false;
   }
   if (this == ob) {
       return true;
   }
   if (ob instanceof User) {
       User other = (User) ob;
       return this.id.equals(other.getId());
   }
   return false;
}

事实证明,对象的唯一性仅由其ID决定。但在我的应用程序中, id 始终是唯一的。它在数据库中提供。我的等于实施是否足以说明这一点?或者这不是最佳做法吗?

It turns out that the uniqueness of an object is determined only by its ID. But in my application, id is always unique. It's provided at the database. Is my equals implementation competent enough to account for this? Or is this not best practice?

当然我理解在这种情况下 hashCode 的实现应该如下:

Of course I understand that in this case the hashCode implementation should be the following:

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


推荐答案

你是否应该这样做取决于关于你班级的语义。也就是说,是什么意思来说你班级的两个对象是等价的?最重要的区别在于具有值语义的对象和具有实体语义的对象之间。实体对象即使具有相同的属性(颜色,长度等)也不相等。在许多情况下,包括从具有主键的数据库表中读取对象时,实体对象将具有唯一的ID字段。在这种情况下仅比较ID字段是正确的做法。

Whether you should do this depends on the semantics of your class. That is, what does it mean to say that two objects of your class are equivalent? The most important distinction is between objects with value semantics and objects with entity semantics. Entity objects are not equivalent even if they have equivalent attributes (colour, length, etc.). In many cases, including when the object has been read from a database table that has a primary key, entity objects will have an ID field that is unique. Comparing only the ID field in that case is the right thing to do.

这篇关于equals()仅依赖于ID是否合适?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆