The moose likes Beginning Java and the fly likes HashSet Raises Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "HashSet Raises Exception" Watch "HashSet Raises Exception" New topic

HashSet Raises Exception

Siamak Saarmann
Ranch Hand

Joined: Aug 21, 2004
Posts: 78

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 Artificial Intelligence, OCJP1.6
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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?

[Jess in Action][AskingGoodQuestions]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
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.



Java API Documentation
The Java Tutorial
Siamak Saarmann
Ranch Hand

Joined: Aug 21, 2004
Posts: 78
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.

Siamak Saarmann
Ranch Hand

Joined: Aug 21, 2004
Posts: 78
Thank you. I found how should I do it. I implemented Comparable and added the compareTo method.

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
subject: HashSet Raises Exception
It's not a secret anymore!