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
You need to correctly implement
hashCode()
andequals()
.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.When ever you create an object of class Accumulator it takes new space in JVM and returns unique hashCode every time you add an object in hashSet. It does not depends upon the value of the object because you have not overridden hashCode() method hence it will call Object class hashCode() method which will return unique hashCode with every object created in your program.
Solution:
Override hashCode() and equals() method and apply your logic depending upon the properties of your class. Be sure to read equals and hashcode contract
http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html