Atma
Atma

Reputation: 29767

Java TreeSet not storing unique values

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?

Upvotes: 2

Views: 2981

Answers (2)

monty
monty

Reputation: 1590

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());
 }

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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.

Upvotes: 1

Related Questions