Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashSet is allowing dupes; problem with comparable?

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

like image 555
IVR Avenger Avatar asked Jun 02 '10 20:06

IVR Avenger


1 Answers

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.

like image 186
Michael Borgwardt Avatar answered Nov 16 '22 13:11

Michael Borgwardt