There are several problems I see with your code:
- Your
removeCats
function is creating an iterator, not using it, then probably exploding with aConcurrentModificationException
because you're removing things from thepets
set while iterating over it. Many of the other answers have pointed this out, and the best way to fix this is to replace this entire function with something likepets.removeAll(cats);
. If you really must use an iterator for some reason, you should be iterating overcats
, and callingpets.remove(cat);
Once this is fixed, you won't crash horribly. However... removeCats
will still not do what you expect, since none of the objects in cats
are actually present in pets
!:
Your
join
function is not doing what I'd expect it to do based on the method signature - it's not joining together the two sets, but instead discarding the inputs and creating a new list. You probably want to do something likepets.addAll(cats); pets.addAll(dogs);
Once you fix this issue, your printPets
function will work properly, and removeCats
will actually have the right effect the way it is being called, since pets
will actually contain cats
, and not some new instances of them.