首页 > 解决方案 > 我们如何为集合实现 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;
    }
}

标签: javaspringhibernatejpa

解决方案


您放入集合中的您自己类型的对象应该具有equalshashCode实现。这正是实施equalshashCode.

你不需要——你不应该——为集合对象实现equalshashCode,即使它们包含其他对象。

您应该为您编写的包含equals集合的对象实现和,并且在这些方法的实现中,您应该使用集合对象的内置和方法。hashCodeequalshashCode


推荐阅读