java - 我们如何为集合实现 equals() 和 hashcode()?
问题描述
描述
建议对经常分离和重新附加的实体实施equals()
和。hashcode()
特别是如果我们使用一个集合或集合。
问题
我还没有看到任何关系示例,那么我们将如何在下面的示例中正确实现这些方法?我们是否还需要一个覆盖标准集合方法的派生集合类?
亲子关系 1:n
/**
* A component which marks a {@link com.artemis.Entity} as a chunk and stores its most valuable information.
*/
@Entity
@Table(name = "chunk")
@Access(value = AccessType.FIELD)
public class Chunk extends HibernateComponent{
public int x;
public int y;
public Date createdOn;
@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name = "chunk_identity", joinColumns = @JoinColumn(name = "identity_id"), inverseJoinColumns = @JoinColumn(name = "id"), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
public Set<Identity> inChunk = new LinkedHashSet<>();
@Transient
public Set<ChunkLoader> loadedBy = new LinkedHashSet<>();
public Chunk() {}
public Chunk(int x, int y, Date createdOn) {
this.x = x;
this.y = y;
this.createdOn = createdOn;
}
}
/**
* Represents a ID of a {@link com.artemis.Entity} which is unique for each entity and mostly the database id
*/
@Entity
@Table(name = "identity")
@Access(AccessType.FIELD)
public class Identity extends Component {
@Id public long id;
public String tag;
public String typeID;
public Identity() {}
public Identity(long id, String tag, String typeID) {
this.id = id;
this.tag = tag;
this.typeID = typeID;
}
}
解决方案
您放入集合中的您自己类型的对象应该具有equals
并hashCode
实现。这正是实施equals
和hashCode
.
你不需要——你不应该——为集合对象实现equals
和hashCode
,即使它们包含其他对象。
您应该为您编写的包含equals
集合的对象实现和,并且在这些方法的实现中,您应该使用集合对象的内置和方法。hashCode
equals
hashCode
推荐阅读
- visual-studio - 无法在 Visual Studio 2019 上启动 Tizen 包管理器
- flutter - 增加键盘和 TextField 之间的空间
- okd - OKD 4.5 - 如何在受限网络中升级集群
- flutter - Flutter 软件包更新造成问题
- java - 抽象类如何访问子类的方法?
- fluentd - 仅通过 fluent-bit 收集具有特定字段的日志
- html - 无法通过 HTML iframe 上的“https://view.officeapps.live.com/op/embed.aspx?src=[MSG 文件 URL]”呈现 .MSG 文件
- python - 运行机器人框架测试而不将其放入模板文件中
- java - 使用eclipse-resource-api(插件开发)遍历maven项目的依赖jar
- python-3.x - django-import-export 如何根据当前用户登录跳过导入一些行?