An exception can be thrown when removing duplicates, because the same set that is iterated over is also modified. The fix is to iterate over a copy of the set.