I have a TreeSet of objects called Artifacts. I have overridden the equals and hash code methods in the object like so:
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(artifactId).
toHashCode();
}
@Override
public boolean equals(Object arg0) {
Artifact obj=(Artifact)arg0;
if(this.getArtifactId().equalsIgnoreCase(obj.getArtifactId()))
{
return true;
}
return false;
}
I have put prints in the equals method and it is never called. I have instantiated the TreeSet with a comparator which looks like:
TreeSet<Artifact> syncedList = new TreeSet<Artifact>(new ArtifactComparator());
I have read that the TreeSet establishes it's uniqueness based on the equals override.
I see multiple objects with the same ArtifactId in the TreeSet which is not unique like I need.
Is something missing in my equals and hash code methods?
As Ernest said, you need a compareTo()
method. If you think about the Tree structure, it doesn't just have to know if two objects are considered equal to each other but if one is "less than" or "greater than" to know where in the tree to place the object relative to the ones already there. i.e. a tree builds an ordered list.
So, you could do away with the ArtifactComparator
class if you wanted, and just make your Artifact class implement Comparable<Object>
, adding the compareTo
method such as below:
@Override
public int compareTo(Object arg0) {
Artifact obj=(Artifact)arg0;
return this.getArtifactId().compareToIgnoreCase(obj.getArtifactId());
}