2

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?

2 Answers 2

2

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());
 }
Sign up to request clarification or add additional context in comments.

Comments

1

TreeMap (and this TreeSet) doesn't use your equals() method at all, except if you fetch the entrySet() or keySet(). If there's a problem, it's going to be in ArtifactComparator. That class's compareTo() must return 0 to indicate that two Artifacts are equal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.