Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet Raises Exception

 
Siamak Saarmann
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

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?

Regards,
Mac
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you can see there is a little bit of confusion here. Can you please post the exact error message you get when you run your program? This will help us be able to answer your question correctly.

Thanks,

Layne
 
Siamak Saarmann
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am terribly sorry. Yes, it has been TreeSet.

So I need to add a comparable method to the class which is going to be stored in TreeSet?

Again I am sorry for the mistake and thank you for your help.

Regards,
Mac
 
Siamak Saarmann
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. I found how should I do it. I implemented Comparable and added the compareTo method.

Regards,Mac
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic