jQuery in Action, 2nd edition*
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 Murach's Java Servlets and JSP this week in the Servlets 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: http://aspose.com/file-tools
subject: HashSet and removeAll()
Similar Threads
new SCJP in town :)
Which collection refuses adding a duplicate?
don't like to hijack or do i ....
Struts 2 validation not working
HashSet and TreeMap