I have a custom object for which I want to define a custom test for equality. I followed the steps in What issues should be considered when overriding equals and hashCode in Java? using the Apache Commons library.
However, the removeAll() method does not work properly when using it on two sets. contains() on a set does work however!
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();
}
For clarity, this is the method used in the equals() and hashCode() methods. It simply cuts off a string given a certain regex.
// strips project key from component string, leaving only the path to the component
public String getRealComponentPath(String rawComponent) {
return rawComponent.replaceAll(project + ":", "");
}
Expected behaviour (Debugging)
int i = 0;
for (Issue issueA : issuesA) {
for (Issue issueB: issuesB) {
if (issueA.equals(issueB)) {
result.add(issueA);
}
if (issuesA.contains(issueB)) {
i++;
}
}
}
When printing i, I get 100 for sample sets A(size=100) and B(size=100), whereas `issuesA.removeAll(issuesB) results in 0 issues being removed.
Please let me know what I am missing.