覆盖equals和hashcode导致removeAll()的行为错误

时间:2016-04-22 14:54:38

标签: java collections equals hashcode

我有一个自定义对象,我想为其定义相等的自定义测试。我使用Apache Commons库跟踪了What issues should be considered when overriding equals and hashCode in Java?中的步骤。

但是,在两个集合上使用removeAll()方法时,它无法正常工作。然而,集合上的contains()确实有效!

private String key;
private String rule;
private String component;
private String project;
private String message;
private TextRange textRange;

@Override
public int hashCode() {
    HashCodeBuilder hashBuilder = new HashCodeBuilder(17, 31);
    hashBuilder.append(rule)
    .append(getRealComponentPath(component))
    .append(textRange.getEndLine())
    .append(textRange.getEndOffset())
    .append(textRange.getStartLine())
    .append(textRange.getStartOffset());
    return hashBuilder.hashCode();
}

@Override 
public boolean equals(Object obj) {
    if (!(obj instanceof Issue))
        return false;
    if (obj == this)
        return true;

    Issue rhs = (Issue) obj;
    return new EqualsBuilder().
        append(rule, rhs.rule).
        append(getRealComponentPath(component), rhs.getRealComponentPath(component)).
        append(textRange.getEndLine(), rhs.textRange.getEndLine()).
        append(textRange.getEndOffset(), rhs.textRange.getEndOffset()).
        append(textRange.getStartLine(), rhs.textRange.getStartLine()).
        append(textRange.getStartOffset(), rhs.textRange.getStartOffset()).
        isEquals();
}

为清楚起见,这是equals()和hashCode()方法中使用的方法。它只是在给定一个正则表达式的情况下切断字符串。

// strips project key from component string, leaving only the path to the component
public String getRealComponentPath(String rawComponent) {
    return rawComponent.replaceAll(project + ":", "");
}

预期行为(调试)

int i = 0;
    for (Issue issueA : issuesA) {
        for (Issue issueB: issuesB) {
            if (issueA.equals(issueB)) {
                result.add(issueA);
            }
            if (issuesA.contains(issueB)) {
                i++;
            }
        }
    }

当打印i时,我得到100个样本集A(大小= 100)和B(大小= 100),而`issuesA.removeAll(issuesB)导致0个问题被删除。

请让我知道我错过了什么。

0 个答案:

没有答案