This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Java in General and the fly likes HashSet and removeAll() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashSet and removeAll()" Watch "HashSet and removeAll()" New topic

HashSet and removeAll()

John Edward

Joined: Oct 14, 2003
Posts: 4
I have a class named Test that overrides both equals() and hashcode() so that a collection of them can be stored in a HashSet with no duplicates.
I have a second class named TestGroup that holds a collection of Test objects in a HashSet.
When I try to add multiple Tests to the TestGroup, the HashSet seems to be preventing the duplicates correctly.
Where I am running into trouble is when I am trying to find and remove all of the elements from one HashSet (insertSet) that are contained in a second (dbSet).
For some reason, the removeAll() method is not removing the matching elements.
Here is some code showing what I am doing:

I'm not sure if the code sample is complete enough for anyone to spot the problem, but let me know if you need more info.
Thanks in advance for any assistance,
John Edward

Joined: Oct 14, 2003
Posts: 4
I'm sorry - I figured this out already.
I had incorrectly implemented the hashCode() method in my Test class. In some intances, Tests that should be considered equal were returning different hashCode values which was preventing the HashSet.removeAll() method from working correctly.
Thanks anyway,
I agree. Here's the link:
subject: HashSet and removeAll()
It's not a secret anymore!