Alex Rivera | Logout

Java HashSet is allowing dupes; problem with comparable?

Asked 2010-06-02T20:28:22.297
9

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

Edit
Report

1 Answer

1

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.

answered 2010-06-02T20:31:09.350

Your Answer