• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparing Objects in a Set?  RSS feed

 
Nate Leech
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm populating a HashSet with a specific Object that I have made called Section.

In a Set, it says that no Object should be added if it already exists in the Set.

However, objects that are identical are still being added. I have added an equals method to my Section object, but it doesn't seem like the equals method even gets called when the object is being added to the set. I have even made sure that all of the instance variables within the Object are equal just in case the add method of the Set is trying to do some other comparison.

Am I going about this all wrong?

Thanks for any help!

-Nate
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you overrode equals(), did you also override the hashCode() method? The API for Object has some rules about how these two methods must be interrelated. If your class does not obey these rules, it will not behave correctly when you use i tin a HashSet or HashMap.
 
Nate Leech
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Jim!

That did the trick!
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For completeness, you might also want to override compareTo. Try adding your objects to a TreeSet (without a separate comparator) and see whether compareTo gets called to put the objects in sorted order.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!