views:

189

answers:

6

Hi, all.

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

+9  A: 

You need to correctly implement hashCode() and equals().

You must override hashCode and return a number based on the values in your class such that any two equal objects have the same hashcode.

SLaks
without equals it would be totally invalid.
Justin
+9  A: 

What am I screwing up, here?

HashSet is based on hashCode(), not on compareTo(). You may be confusing it with TreeSet. In both cases, be sure to also implement equals() in a manner that is consistent with the other method.

Michael Borgwardt
+1  A: 

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.

sblundy
You only need to override hashCode if equals is overridden (definition is equality has changed). The other way around is not necessarily true. It's perfectly legal to change hashCode to return 1 and leave equals alone.
Steve Kuo
+2  A: 

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

Luno
+1  A: 

Your objects are Comparable, and probably you've implemented equals() too, but HashSets deal with object hashes, and odds are you haven't implemented hashCode() (or your implementation of hashCode() doesn't return the same hash for two objects that are (a.equals(b) == true).

Edwin Buck
+1  A: 

HashSet uses the hashCode() and equals() 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 the equals() method to see if any identical objects already exist in the set.

Your debugger is not breaking on compareTo() because it is never used with HashSet!

The rules are:

  1. If two objects are equal, then their hash codes must be equal.

  2. 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.

Michael Angstadt