I have a class Person which I want to use with a HashSet collection.
When I add first item , it does not complain but when adding second one it raises an exception.
Tutorial says this happens when HashSet is not able to compare two objects added to collection. How can I add this compare feature to my Person class (I have already added the hashCode and equal methods).
In .NET there was a comparable interface which we needed to implement.
What should I do in Java?
PhD Candidate: Distributed and Parallel Systems, Simulation and Modeling
Java does the same thing. Look up Comparable or Comparator in the JavaDoc. Comparable adds features to the objects you're putting in the collection, Comparator does the same work in another object. The common form for comparable is something like:
It's a good idea to make sure the equals() method agrees with this one on what is equal and what isn't.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Everything that Stan says is correct, but -- HashSet does not require the elements it contains to implement Comparable, and HashSet.add() won't throw an exception under normal circumstances. The behavior you're describing -- and Stan's solution -- are appropriate to TreeSet, not HashSet -- perhaps that's what you meant to say?