Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - TreeSet and hashCode()

Tags:

I have a quick question about TreeSet collections and hashCode methods. I have a TreeSet and I'm adding objects to it, before I add an object, I check to see if it exists in the TreeSet using the contains method.

I have 2 distinct objects, each of which produce a distinct hashCode using my implementation of the hashCode method, example below:

public int hashCode()
{
    int hash = 7;
    hash = hash * 31 + anAttribute.hashCode();
    hash = hash * 31 + anotherAttribute.hashCode();
    hash = hash * 31 + yetAnotherAttribute.hashCode();
    return hash;
}

The hashCodes for a particular run are: 76126352 and 76126353 (the objects only differ by one digit in one attribute).

The contains method is returning true for these objects, even though the hashCodes are different. Any ideas why? This is really confusing and help would really be appreciated.

like image 203
Gaz Avatar asked Sep 24 '09 09:09

Gaz


People also ask

Does TreeSet use hashCode?

TreeSet does not use hashCode at all. It uses either compareTo or the Comparator you passed to the constructor. This is used by methods like contains to find objects in the set.

Does TreeMap use hashCode?

hashCode and equals method are not required for TreeSet and TreeMap as the sorting depends on either the compareTo or compare method as been provided by the client.

Does TreeSet use hashing?

HashSet is Implemented using a hash table. TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet.

What is difference between HashSet and TreeSet in Java?

Hash set and tree set both belong to the collection framework. HashSet is the implementation of the Set interface whereas Tree set implements sorted set. Tree set is backed by TreeMap while HashSet is backed by a hashmap.


1 Answers

TreeSet does not use hashCode at all. It uses either compareTo or the Comparator you passed to the constructor. This is used by methods like contains to find objects in the set.

So the answer to your question is that your compareTo method or your Comparator are defined so that the two objects in question are considered equal.

From the javadocs:

a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

like image 90
sepp2k Avatar answered Sep 28 '22 08:09

sepp2k