Because you're deleting the element and then immediately adding the same element back during the forEach
loop, the Set gets modified in a way that causes the added element to be treated as a new item to iterate. Since foreach continues iterating over newly added elements during the same loop, this creates an infinite cycle: the element gets re-added, queued for iteration again, and the loop never ends, leading to a dead loop or infinite loop.