Is it possible to overwrite some HashSet element (not necessarily the one iterated) while iterating over it. I want to know of a way apart from removing, editing and then re-adding it?
The reason I am asking this is because using remove while iterating always gives the java.util.ConcurrentModificationException. I figured out that there is no method to overwrite a set element.
Any help will be appreciated.
Thanks,
Somnath
You can remove an item from a
Collection– including aSet– whilst iterating over it as long as you iterate over it using anIteratorand callItertator.remove()to do the remove. However, this will only allow you to remove the current item in the iteration.You can’t remove another item or add one as this will cause a
ConcurrentModificationException, since if you change theSetit’s not clear how you would iterate over it.Also, unlike a
List, is doesn’t quite make sense to talk about replacing an entry in aSet. In aListitems have a define order so, for example, if the second entry was “A” you could replace it with “B”. Items in aSetdon’t have an order so you can’t replace one with another directly, all you can do is remove the old one and add the new one.Depending quite on what you want to do, your best approach might be to loop over a copy of the
Set:However, you’d have to account for the fact that the objects you iterated over would be the original values and wouldn’t reflect any changes you’d made.
If this won’t do, then it might make sense to find another way of process the items in the
Setwithout simply iterating over them by keeping track of which nodes you’ve processed.Something like this might do but could probably be improved depending on what you’re doing: