I've got a class, "Accumulator", that implements the Comparable compareTo method, and I'm trying to put these objects into a HashSet.
When I add() to the HashSet, I don't see any activity in my compareTo method in the debugger, regardless of where I set my breakpoints. Additionally, when I'm done with the add()s, I see several duplicates within the Set.
What am I screwing up, here; why is it not Comparing, and therefore, allowing the dupes?
Thanks,
IVR Avenger
When hashCode return different values for 2 objects, then equal is not used. Btw, compareTo has nothing to do with hashing collections :) but sorted collections
HashSet uses hashCode and equals. TreeSet uses the Comparable interface. Note: if you decide to override either hashcode or equals, you should always override the other.
Your objects are
Comparable
, and probably you've implementedequals()
too, butHashSets
deal with object hashes, and odds are you haven't implementedhashCode()
(or your implementation ofhashCode()
doesn't return the same hash for two objects that are(a.equals(b) == true)
.HashSet is based on
hashCode()
, not oncompareTo()
. You may be confusing it withTreeSet
. In both cases, be sure to also implementequals()
in a manner that is consistent with the other method.HashSet uses the
hashCode()
andequals()
methods to prevent duplicates from being added. First, it gets the hash code of the object you want to add. Then, it finds the corresponding bucket for that hash code and iterates through each object in that bucket, using theequals()
method to see if any identical objects already exist in the set.Your debugger is not breaking on
compareTo()
because it is never used withHashSet
!The rules are:
If two objects are equal, then their hash codes must be equal.
But if two objects' hash codes are equal, then this doesn't mean the objects are equal! It could be that the two objects just happen to have the same hash.
One thing which people tends to ignore which result in a huge mistake. While defining equals method always take the parameter as object class and then conver the object to your desired class. For eg
If u pass write Song aSong instead of Object aSong your equals method will never get called.
Hope this helps